Javascript Reference - JavaScript Date Constructor








The JavaScript Date type stores dates as the number of milliseconds since midnight on January 1, 1970 UTC (Universal Time Code).

Browser Support

constructor Yes Yes Yes Yes Yes

Example

To create a date object:

//created object aDate is assigned the current date and time.
var aDate = new Date(); 
console.log(aDate)

To create a date with the number of milliseconds after midnight, January 1, 1970 UTC.


var aDate = new Date(1111111); 
console.log(aDate);
//Wed Dec 31 1969 16:18:31 GMT-0800 (Pacific Standard Time)





Example 2

We can pass in a string value representing the date value.

The following date formats are supported:

FormatExample
month/date/year 7/24/2012
month_name date, yearJanuary 31, 2021
day_of_week month_name date year hours:minutes:seconds time_zoneTue May 27 2012 12:34:56 GMT-0400
ISO 8601 extended format YYYY-MM-DDTHH:mm:ss.sssZ2012-0525T00:00:00

var aDate = new Date("May 25, 2004"); 
console.log(aDate);
//Tue May 25 2004 00:00:00 GMT-0700 (Pacific Daylight Time)

The code above generates the following result.





Example 3

We can pass in numbers to Date class constructors.

  • the year,
  • the zero-based month (January is 0, February is 1, and so on)
  • the day of the month (1 through 31),
  • the hours (0 through 23),
  • minutes,
  • seconds,
  • milliseconds

The year and month are required.


var aDate = new Date(2012, 4, 5, 17, 55, 55); 
console.log(aDate);
//Sat May 05 2012 17:55:55 GMT-0700 (Pacific Daylight Time)

The code above generates the following result.

Example 4

If the day of the month isn't supplied, it's assumed to be 1. all other omitted arguments are assumed to be 0.

var aDate = new Date(2012, 0); 
console.log(aDate);
//Sun Jan 01 2012 00:00:00 GMT-0800 (Pacific Standard Time)