find current date with format yy-mm-dd in typescript

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.ts
const currentDate = new Date();

const year = currentDate.getFullYear();
const month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
const day = ('0' + currentDate.getDate()).slice(-2);

const formattedDate = `${year}-${month}-${day}`;

console.log(formattedDate); // Output: "2022-02-01"
291 chars
10 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