WDN Logo

home-icon Home / JavaScript / Formatting time and date using JavaScript

Formatting time and date using JavaScript

Formatting time and date using JavaScript

JavaScript has an inbuilt support for dates and times with its Date object. The methods of the Date object return various values associated with date and time.

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.

Sponsored Links

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.

Format #1: date-month-year

The three methods that we would be using are:

  • getDate(): Returns the date
  • getMonth(): Returns the month
  • getFullYear(): Returns the year
<script type="text/javascript">
<!--

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

document.write(curr_date + "-" + curr_month + "-" + curr_year);

//-->
</script>

This prints:

In the code above, we have a different variable for the day, month and year. These variables all contain numeric quantities. (You can check this using typeof()). Hence, you can perform any kind of numerical operations on these variables.

The eagle-eyed would have noticed that the month value returned by getMonth() is one less than the current month. This is because months start at 0 value, thus, January is represented by 0, February as 1, March as 2 …
We would have to increment the value returned by getmonth() by 1. The corrected lines of code are:

<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
//-->
</script>

This prints:

Format #2: month/day/year

This is very similar to the above:

<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year);
//-->
</script>

This prints:

Sponsored Links

Search

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

joke-how-people-run-how-programmer-run

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

Apple's iTunes Music Store did not carry original songs by Beatles for many years. However, on the 16th of November 2010, the entire Beatles catalog was released. [more...]

Share on Whats app Share on Facebook Share on Twitter Share on Google plus