convert date to "yyyy-mm-dd" in typescript

To convert a date to the "yyyy-mm-dd" format in TypeScript, we can use the toLocaleDateString() method. This method returns a string representation of the date, formatted according to the provided options.

Here's an example code snippet:

index.ts
const date = new Date(); // get the current date
const formattedDate = date.toLocaleDateString("en-US", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});
console.log(formattedDate); // output: "2022-08-08"
219 chars
8 lines

In the code above, we first create a new Date object to get the current date. We then call the toLocaleDateString() method on this object and pass in two arguments:

  • The first argument is the locale - in this case, "en-US".
  • The second argument is an object containing the formatting options. We specify the year to be displayed in 4-digit format, and the month and day to be displayed in 2-digit format. We also separate them with a hyphen ("-"), which results in the desired "yyyy-mm-dd" format.

Finally, we log the formatted date string to the console.

gistlibby LogSnag