Saturday, April 30, 2011

JavaScript Date and Time - XVIII


JavaScript provides you with the ability to access the date and time of your users' local computer, which can be quite useful at times. Displaying the current date and time in a nice user friendly way using JavaScript is not quite as simple as you might like. You need to massage the data a little.

Displaying the Current Date

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...
30/3/2011

Displaying the Current Time

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...
8:50
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.

Displaying the Current Time in AM/PM Format

Typing this code...
var currentTime = new Date()
  var hours = currentTime.getHours()
  var minutes = currentTime.getMinutes()

  var suffix = "AM";
  if (hours >= 12) {
  suffix = "PM";
  hours = hours - 12;
  }
  if (hours == 0) {
  hours = 12;
  }

  if (minutes < 10)
  minutes = "0" + minutes

  document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
Results in this...
8:50 AM

No comments:

Post a Comment