MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript current time and date

Use new Date() to generate a new Date object containing the current date and time.

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


var year = (new Date()).getFullYear();
console.log(year)

Output


Get the current month


var month = (new Date()).getMonth();
console.log(month);

Output

Please note that 0 = January, 1= February. This is because months range from 0 to 11, so it is often desirable to add +1 to the index.

Get the current day


var day = (new Date()).getDate();
console.log(day);

Output

Get the current hour


var hours = (new Date()).getHours();
console.log(hours);

Output

Get the current minutes


var minutes = (new Date()).getMinutes();
console.log(minutes);

Output

Get the current seconds


var seconds = (new Date()).getSeconds();
console.log(seconds);

Output

Get the current milliseconds

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


var milliseconds = (new Date()).getMilliseconds();
console.log(milliseconds);

Output


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


var now = new Date();
console.log(now.toUTCString());

Output

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.


console.log(Date.now());
console.log((new Date()).getTime());

Output



Conclusion

In this page (written and validated by ) you learned about Javascript current time and date . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Increment a Date Object.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.