date to string including time with milliseconds in typescript

To convert a Date object to a string that includes time with milliseconds in TypeScript, you can use the toISOString() method of the Date object and then use string manipulation to remove the trailing "Z" character and concatenate the milliseconds part.

Here's an example code snippet that demonstrates this:

index.ts
const date = new Date();
const dateTimeString = date.toISOString().replace("Z", "").replace("T", " ");
const timeWithMilliseconds = dateTimeString.substring(dateTimeString.length - 4);
const dateString = dateTimeString.substring(0, dateTimeString.length - 4);

const fullDateTimeString = `${dateString}${timeWithMilliseconds}`;
console.log(fullDateTimeString);
361 chars
8 lines

In this code snippet, we first create a Date object with the current date and time. We then use the toISOString() method to get a string representation of that date, which includes the date, time, and milliseconds in ISO 8601 format.

Next, we use string manipulation to remove the trailing "Z" character (which indicates that the date is in UTC time), replace the "T" character with a space, and extract the milliseconds part of the string.

Finally, we concatenate the date string (without milliseconds) with the time string (with milliseconds) to get a full date/time string with milliseconds included.

This should output a string like this: "2021-05-20 16:42:30.2353".

gistlibby LogSnag