How do I get the current date in JavaScript in specific format?

Alexandr Ursu
1 min readJan 7, 2021
format date with vanilla JavaScript

There are very good packages to use when working with Date and Time and I would highly recommend using one and to not reinvent the wheel if you have a very complex logic to implement. Checkout moment.js or date-fns.

But there are time when we need a simple Date operation and we don’t want an extra dependency for that. One use case will be to get today’s date and format for example mm/dd/yyyy. The solution would be to use javascript Date Object to generate a new Date() object containing the current date and time:

// format date as mm/dd/yyyy
let today = new Date();
let d = today.getDate();
let m = today.getMonth() + 1; //Months starts from 0 to 11
let y = today.getFullYear();
// use .padStart to add 0 in front of single digit numbers
let dd = String(d).padStart(2, “0”);
let mm = String(m).padStart(2, “0”);
let yyyy = today.getFullYear();
today = mm + “/” + dd + “/” + yyyy;
document.write(today);

That’s it, happy hacking and do not forget to clap if it was useful!

--

--