To get the current date with the required format yy-mm-dd in TypeScript, you can use the toLocaleDateString
method of the Date
object with appropriate formatting options as shown below:
index.ts291 chars10 lines
In the above code, the getFullYear
method of the Date
object is used to get the current year in the YYYY format. The getMonth
method returns the zero-based index of the month, so we add 1 to it and then prefix a '0' using the slice
method to ensure that the month is always a two-digit value. Similarly, the getDate
method is used to get the current day of the month and once again, a '0' prefix is added if necessary. Finally, the string interpolation syntax is used to concatenate these values in the required format.
Note that this method retrieves the current date based on the user's system settings, which means that the date may be different depending on the user's time zone or location. If you require a date from a specific time zone or location, you will need to use a library like Moment.js or Luxon.
gistlibby LogSnag