'How to convert "YYYY-MM-DD" format to Date object
I have date in the format of "YYYY-MM-DD" i need to convert it into Mon Feb 21 2022 05:30:00 GMT+0530 (India Standard Time) format
Solution 1:[1]
You just need to use new Date()
new Date('2022-02-17')
Solution 2:[2]
To answer the question in the title, you can simply just initialize a Date object by using the string you have
const date = new Date("2022-02-17");
Now formatting it into something else can be a tedious to do. Using library such as date-fns would be easier.
Javascript has a native method closer to what you want:
new Date("2022-02-17").toLocaleString('hi-IN', { timeZone: "Asia/Kolkata" })
will return: '17/2/2022, 5:30:00 am'.
Now formatting it to something else IMO should be in a different question since the title of this question is already answered.
Solution 3:[3]
I would recommend using Luxon for date manipulation in Javascript.
import { DateTime } from 'luxon';
const dt = new DateTime.fromISO("2022-02-17");
const formatted = dt.toLocaleString(DATETIME_FULL);
In your question the date you want to convert it to is 4 days ahead. If this isn't a typo, you can also add days to the date object like this:
const addDays = dt.plus({ days: 4 });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hao-Jung Hsieh |
| Solution 2 | doesnotmatter |
| Solution 3 | user3536141 |
