Note that Date() called without arguments is equivalent to new Date(Date.now()).
Once you have a date object, you can apply any of the several available methods to extract its properties (e.g.
getFullYear() to get the 4-digits year).
Below are some common date methods.
Get the current year
Code: Select all
var year = (new Date()).getFullYear();
console.log(year);
Get the current month
Code: Select all
var month = (new Date()).getMonth();
console.log(month);
Please note that 0 = January. This is because months range from 0 to 11, so it is often desirable to add +1 to the
index
Get the current day
Code: Select all
var day = (new Date()).getDate();
console.log(day);
Get the current hour
Code: Select all
var hours = (new Date()).getHours();
console.log(hours);
Get the current minutes
Code: Select all
var minutes = (new Date()).getMinutes();
console.log(minutes);
Get the current seconds
Code: Select all
var seconds = (new Date()).getSeconds();
console.log(second);
Get the current milliseconds
To get the milliseconds (ranging from 0 to 999) of an instance of a Date object, use its getMilliseconds method.
Code: Select all
var milliseconds = (new Date()).getMilliseconds();
console.log(milliseconds);
Convert the current time and date to a human-readable string
Code: Select all
var now = new Date();
// convert date to a string in UTC timezone format:
console.log(now.toUTCString());
The static method Date.now() returns the number of milliseconds that have elapsed since 1 January 1970 00:00:00
UTC. To get the number of milliseconds that have elapsed since that time using an instance of a Date object, use its
getTime method.
Code: Select all
// get milliseconds using static method now of Date
console.log(Date.now());
// get milliseconds using method getTime of Date instance
console.log((new Date()).getTime());