change date "oct 11, 2022" to yyyy-mm-dd in javascript

You can change the format of the date from "oct 11, 2022" to "yyyy-mm-dd" using the following approach:

index.tsx
const originalDateString = "oct 11, 2022";
const originalDate = new Date(originalDateString);
const year = originalDate.getFullYear();
const month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
const day = ("0" + originalDate.getDate()).slice(-2);
const formattedDate = year + "-" + month + "-" + day;
console.log(formattedDate); // Output: 2022-10-11
356 chars
8 lines

In the code above, the Date() constructor is used to create a date object from the original date string. Then, the getFullYear(), getMonth(), and getDate() methods are used to extract the year, month, and day from the date object, respectively.

Since the getMonth() method returns a zero-based index for the month, 1 is added to the result to get the actual month number. The slice(-2) method is used to ensure that the month and day values are always two digits long. Finally, the year, month, and day values are concatenated with hyphens to form the final formatted date string.

gistlibby LogSnag