WebDevelopersNotes logo

home-icon Home / JavaScript / Date and Time in JavaScript

Date and Time in JavaScript

Date and Time in JavaScript

The date object is very useful for obtaining the date and time on the client. It supports various methods, which return a specific value.

To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the variable. Here is the code:

var d = new Date();

Thus, variable d contains a new date object. We can now call the various methods of this date object.

var t_date = d.getDate();      // Returns the day of the month
var t_mon = d.getMonth();      // Returns the month as a digit
var t_year = d.getFullYear();  // Returns 4 digit year
var t_hour = d.getHours();     // Returns hours
var t_min = d.getMinutes();    // Returns minutes
var t_sec = d.getSeconds();    // Returns seconds
var t_mil = d.getMilliseconds();  // Returns Milliseconds

Now we can easily display the date, month and year in an alert box, using the values stored in respective variables.

alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);

Click here to display the alert box

The eagle-eyed would have noticed that the month digit is one less than the present month. Hence, if you want to display the month, increment the value returned by getMonth() by 1. The corrected code should be:

t_mon++;
alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);

Check the results

Similarly, we can get the time using the variables that store hours, minutes, seconds and milliseconds values.

alert("The time is " + t_hour + ":" + t_min + ":" + t_sec);

Get time in an alert box

In the next session we’ll see how we can display a greeting based on the client time.

Sponsored Links

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Don't believe everything you read on the Internet

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

YouTube was serving more than 2 billion videos each day in March 2010. By January 2012, more than 4 billion videos per day were being watched on YouTube. [more...]

We use cookies to give you the best possible website experience. By using WebDevelopersNotes.com, you agree to our Privacy Policy