Create Date object in Javascript
Description
Javascript Date type stores dates as the number of milliseconds that have passed since midnight on January 1, 1970 UTC (Universal Time Code).
Current Date
To create a date object representing the current date and time:
var now = new Date();
console.log(now);
The code above generates the following result.
From millisecond
To create a date from the millisecond passed after midnight, January 1, 1970 UTC.
var aDate = new Date(1234567890);
console.log(aDate);
The code above generates the following result.
From string
For instance, to create a date object for May 25, 2004, you can use the following code:
var someDate = new Date("May 25, 2004");
console.log(someDate);
If the string doesn't represent a date, then it returns NaN.
The code above generates the following result.
From now
var start = Date.now();
console.log(start);
The code above generates the following result.
From parts
We can pass in the following date part to constructor to create Date object
- year,
- zero-based month (January is 0, February is 1, and so on),
- day of the month (1 through 31),
- hours (0 through 23)
- minutes
- seconds
- milliseconds
Of these arguments, only year and month are required.
If the day of the month isn't supplied, it's assumed to be 1, while all other omitted arguments are assumed to be 0.
//January 1, 2000 at midnight in local time
var y2k = new Date(2000, 0);
console.log(y2k);/* ww w .j a v a 2s . c o m*/
//May 5, 2005 at 5:55:55 PM local time
var aDate = new Date(2005, 4, 5, 17, 55, 55);
console.log(aDate);
The code above generates the following result.