Get current date and time in JavaScript
This post will discuss how to get the current date and time in JavaScript.
To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions.
|
1 2 3 4 5 6 7 8 9 10 |
// create a new `Date` object var today = new Date(); // get the date and time var now = today.toLocaleString(); console.log(now); /* Output: 1/27/2020, 9:30:00 PM */ |
The toLocaleString() can be customized using the locales and the options argument:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var today = new Date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; options.timeZone = 'UTC'; options.timeZoneName = 'short'; var now = today.toLocaleString('en-US', options); console.log(now); /* Output: Monday, January 27, 2020, UTC */ |
To display only the date in a specific format, you can use the toLocaleDateString() method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
// create a new `Date` object var today = new Date(); // get today's date in `MM/DD/YYYY` format var now = today.toLocaleDateString('en-US'); console.log(now); /* Output: 1/27/2020 */ |
To display only the time, you can use the toLocaleTimeString() method.
|
1 2 3 4 5 6 7 8 9 10 |
// create a new `Date` object var today = new Date(); // get time in en-US locale var now = today.toLocaleTimeString('en-US'); console.log(now); /* Output: 9:30:00 PM */ |
If you’re already using the Moment.js library, consider using the format() method to parse a moment.
|
1 2 3 4 5 6 7 8 9 |
var moment = require('moment'); // get month name, day of month, year, time var now = moment().format("DD/MM/YYYY HH:mm:ss A"); console.log(now); /* Output: 27/01/2020 21:30:00 PM */ |
That’s all about getting the current date and time in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)