Get current date in JavaScript
This post will discuss how to get the current date MM/DD/YYYY format in JavaScript.
1. Using Date() constructor
The Date() constructor constructs a new Date object representing the current date and time. The Date class has several utility methods to get the current date, month, and year to extract the date information. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// create a new `Date` object var today = new Date(); // `getDate()` returns the day of the month (from 1 to 31) var day = today.getDate(); // `getMonth()` returns the month (from 0 to 11) var month = today.getMonth() + 1; // `getFullYear()` returns the full year var year = today.getFullYear(); // output today's date in `MM/DD/YYYY` format console.log(`${month}/${day}/${year}`); /* Output: 1/27/2020 */ |
2. Using toLocaleDateString() method
The toLocaleDateString() method returns a string representing the date portion of the given Date instance according to language-specific conventions. To get month-day-year order, use en-US locale, 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 */ |
3. Using Moment.js Library
If you’re already using the Moment.js library, consider using the format() method, which accepts the desired format to parse a moment.
|
1 2 3 4 5 6 7 8 9 |
var moment = require('moment'); // get today's date in `MM/DD/YYYY` format var now = moment().format("MM/DD/YYYY"); console.log(now); /* Output: 01/27/2020 */ |
That’s all about getting the current date 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 :)