Get the current time and date

suggest change

Use new Date() to create a Date for the current instant. Date() without new returns a string, not a Date.

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

const year = (new Date()).getFullYear();
console.log(year);
// Sample output: 2016

Get the current month

const month = (new Date()).getMonth();
console.log(month);
// Sample output: 0

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 of the month

const day = (new Date()).getDate();
console.log(day);
// Sample output: 31

Get the current hour

const hours = (new Date()).getHours();
console.log(hours);
// Sample output: 10

Get the current minutes

const minutes = (new Date()).getMinutes();
console.log(minutes);
// Sample output: 39

Get the current seconds

const seconds = (new Date()).getSeconds();
console.log(seconds);
// Sample output: 48

Get the current milliseconds

To get the milliseconds (ranging from 0 to 999) of an instance of a Date object, use its getMilliseconds method.

const milliseconds = (new Date()).getMilliseconds();
console.log(milliseconds);
 // Output: milliseconds right now

Convert the current time and date to a human-readable string

const now = new Date();
// convert date to a string in UTC timezone format:
console.log(now.toUTCString());
// Output: Wed, 21 Jun 2017 09:13:01 GMT

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.

// 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());

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents