DEV Community

loading...
Cover image for How do I get the current date in JavaScript?

How do I get the current date in JavaScript?

courseprobe profile image Course Probe ・2 min read

In this short JS tutorial , let’s find out different ways to get today’s date in javascript.

There might be some easy ways of getting the current date in javascript using some libraries, but some times for some projects it’s better just to use vanilla js.

Let’s see some examples of Javascript get date or javascript date now.

Example 1:

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

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);
Enter fullscreen mode Exit fullscreen mode

Example 2:

If you just want a date without time info, use:

var today = new Date();
    today.setHours(0, 0, 0, 0);

document.write(today);
Enter fullscreen mode Exit fullscreen mode

Example 3:

var date = new Date().toLocaleDateString("en-US");
Enter fullscreen mode Exit fullscreen mode

Also, you can call method toLocaleDateString with two parameters:

var date = new Date().toLocaleDateString("en-US", {
    "year": "numeric",
    "month": "numeric"
});
Enter fullscreen mode Exit fullscreen mode

Additional Resources:

Get the book: Learn Javascript in 59 minutes

source: https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript


Other Dev posts:

Discussion (0)

pic
Editor guide