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.ts134 chars5 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