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

You can format a date into the desired string format using the toLocaleString method. Here's an example:

index.ts
const date = new Date();
const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false,
});

console.log(formattedDate); // outputs something like '2022-03-10 15:30:45.123'
298 chars
13 lines

In the toLocaleString method, we pass the desired locale (in this case, en-US) along with an object that specifies the desired formatting options. By setting hour12 to false, we ensure that the hour is displayed in 24-hour format.

gistlibby LogSnag