UX Design and Development course

Working with date objects

Let's make a JavaScript clock

var fullDate = new Date();

var printTime = function() {
  var nowTime = new Date();
  var date = nowTime.getDate();

  // Because there is not a calendar anywhere that goes from 0 - 11?
  var month = nowTime.getMonth() + 1;

  var fullYear = nowTime.getFullYear();
  var hours = nowTime.getHours();
  var minutes = nowTime.getMinutes();

  // Because there is not a clock anywhere that goes from 0 - 59?
  var seconds = nowTime.getSeconds() + 1;

  console.log(month + ' / ' + date + ' / ' + fullYear + '  ' + hours + ' : ' + minutes + ' : ' +  seconds);
};

// Call in the function to make the clock
setInterval( function() { printTime(); }, 1000 );

All the date object methods https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Pass parameters in setInterval function

You may see examples where the function is passed in via a string into the setInterval function. This is incorrect!

setInterval('printTime()`, 1000 );

You need to create an anonymous function so the actual function isn't executed right away.

setInterval( function() { printTime(); }, 1000 )

Play with code

JS Bin