Wednesday, February 16, 2011

JavaScript Date and Time Functions Examples

JavaScript provides the following date and time functions. Note that UTC stands for Universal Coordinated Time which refers to the time as set by the World Time Standard. Previously referred to as Greenwich Mean Time or GMT.
Displaying the Current Date :
1:Typing this code...


var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth()
  var year = currentDate.getFullYear()
  document.write("<b>" + day + "/" + month + "/" + year + "</b>")
Results in this...
16/2/2011


Displaying the Current Time :
2:Typing this code...

var currentTime = new Date()
  var hours = currentTime.getHours()
  var minutes = currentTime.getMinutes()
  if (minutes < 10)
  minutes = "0" + minutes
  document.write("<b>" + hours + ":" + minutes + " " + "</b>")
Results in this...
16:55
You may have noticed that we had to add a leading zero to the minutes part of the date if it was less than 10. By default, JavaScript doesn't display the leading zero. Also, you might have noticed that the time is being displayed in 24 hour time format. This is how JavaScript displays the time. If you need to display it in AM/PM format, you need to convert it.

0 comments:

Post a Comment

Share