Javascript - How to format a date

You can get an instance of the date object with the current time and date using let date = new Date();. If you call .toString() on this date object you will get a format depending on your locale, mine is "Sun Jan 15 2023 23:01:49 GMT+0100 (Central European Standard Time)". That is a lot of information for a date and time!

Sadly there is no built-in way to format date and time using a string like in most frameworks. You will have to do a bit of string concatenation, for example the below creates the format 'yyyy-MM-dd':

let prefixIfLessThanTen = function(integer){
   return integer < 10 ? ('0' + integer) : integer;
};

let date = new Date();
let year = date.getFullYear();
let month = prefixIfLessThanTen(date.getMonth()+1); //Month is 0 based
let day = prefixIfLessThanTen(date.getDate());
console.log(`${year}-${month}-${day}`);

As this post is being written on the 20th of January 2023 the above will be 2023-01-20. If we want to include time we can do the following:

let prefixIfLessThanTen = function(integer){
   return integer < 10 ? ('0' + integer) : integer;
};

let date = new Date();
let year = date.getFullYear();
let month = prefixIfLessThanTen(date.getMonth()+1); //Month is 0 based
let day = prefixIfLessThanTen(date.getDate());
let hour = prefixIfLessThanTen(date.getHours());
let minute = prefixIfLessThanTen(date.getMinutes());
let seconds = prefixIfLessThanTen(date.getSeconds());
console.log(`${year}-${month}-${day} T${hour}:${minute}:${seconds}`);

As of the writing of this, the time is 08:06 so the above will output 2023-01-20 T08:06:21. If you want UTC time you can use the UTC version of every method:

let prefixIfLessThanTen = function(integer){
   return integer < 10 ? ('0' + integer) : integer;
};

let date = new Date();
let year = date.getUTCFullYear();
let month = prefixIfLessThanTen(date.getUTCMonth()+1); //Month is 0 based
let day = prefixIfLessThanTen(date.getUTCDate());
let hour = prefixIfLessThanTen(date.getUTCHours());
let minute = prefixIfLessThanTen(date.getUTCMinutes());
let seconds = prefixIfLessThanTen(date.getUTCSeconds());
console.log(`${year}-${month}-${day} T${hour}:${minute}:${seconds}`);

Yes, this is a lot of code, but without using a library like moment.js or day.js you are stuck with this. You can make locale specific date formats using toLocaleDateString see this stack overflow post for that.

That is all!

I hope you found this helpful, feel free to leave a comment down below with your thoughts!