format a date in to the format 'yyyy-mm-dd hh:mm:ss.fff' in javascript

In Javascript, we can format a date to the desired format using the toLocaleString() method. However, this method does not support milliseconds.

To format a date with milliseconds, we can use the moment.js library.

Here is an example code using moment.js to format a date:

index.tsx
// get the current date
let date = new Date();

// format it using moment.js
let formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss.SSS');
console.log(formattedDate); // Output: 2022-06-13 14:24:09.364
208 chars
7 lines

In the code above, we first created a new Date object representing the current date and time. We then passed this object to moment() function, which created a moment object that we could use to format the date with the desired format.

The format() method of the moment object takes a string argument that specifies the format. In the example above, we used the format string 'YYYY-MM-DD HH:mm:ss.SSS' to format the date into the format 'yyyy-mm-dd hh:mm:ss.fff'.

The output of the code is the formatted date string: 2022-06-13 14:24:09.364.

gistlibby LogSnag