format a date in to the format 'yyyy-mm-dd' in typescript

In TypeScript, you can format a date into the 'yyyy-mm-dd' format by using the toISOString() method of the Date object and extracting the date part of the resulting ISO string. Here's an example:

index.ts
const date = new Date();
const formattedDate = date.toISOString().substr(0, 10);

console.log(formattedDate); // output: "yyyy-mm-dd"
134 chars
5 lines

In this code, we create a new Date object with the current date and time. We then call the toISOString() method to get an ISO string representation of the date, which looks something like "yyyy-mm-ddThh:mm:ss.sssZ". Finally, we extract the first 10 characters of the string using the substr() method to get just the date part in the format "yyyy-mm-dd".

Note that the toISOString() method returns the date and time in UTC timezone. If you need to format the date in a different timezone, you can use a library like moment-timezone to do the conversion.

gistlibby LogSnag