Categories:

Date, time, and creating a live clock in JavaScript

If you were like me, before I learned JavaScript, one of the most eager things I wanted to know was how to access the time using JavaScript-displaying it, working with it and so on. Well, it was, in fact very easy, and I'll tell you why. JavaScript already has a built in object that gets the date and time for you -all you have to do is use it!

The Date Object

To use this date object, you need to first create an instance of it. Uh? Instant noodles? Well, not quite. What we have to do is tell JavaScript to activate this object:

To activate a Date Object so you can use it, do this:

var mydate= new Date()

Whenever you want to create an instance of the date object, use this important word: new followed by the object name(). Now, I'm going to list some of the methods of the date object that you can use:

Some methods for the date object:
getDate()   returns the day of the month
getDay()   Returns the day of the week
getHours()   returns the hour (Starts from 0-23)!
getMinutes()   returns the minutes
getSeconds()   returns the seconds
getMonth()   returns the month. (Starts from 0-11)!
getFullYear()   returns the year
getTime()   returns the complete time (in really weird format)

Ok, lets say we want to write out today's date:

var today_date= new Date()
var myyear=today_date.getYear()
var mymonth=today_date.getMonth()+1
var mytoday=today_date.getDate()

document.write("Today's date is: ")
document.write(myyear+"/"+mymonth+"/"+mytoday)

output:

  • Come back tomorrow, and the date shown will be different.
  • Lets have a look at the codes in red. "today_date" is the instance of the date object- you could name it anything you want. After creating an instance, that instance can use all the methods. So:
    var myyear=today_date.getFullYear()
    means "get the year and put it in variable myyear."
  • We added "1" to the month, since in JavaScript, it counts months starting from "0", not "1".
  • The date() object of JavaScript always uses the user's local PC's date and time for its information. So different users may see a different date/time, depending on where in the World he/she is located.