Convert date string to a date object

All we need is an easy explanation of the problem, so here it is.

Getting the date from the user and storing the value as a string variable. The value looks like this Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)

I want to convert that string again into a new Date() object for further configurations (I need to add the number of days to the selected date and show it on another Angular mat-datepicker)
How can I do this..?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can cast a date string directly to a Date object like:

let myDate = new Date("Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)");

You can manipulate your date as follows:

// For instance adding a day:
let today = new Date("Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)");

let tomorrow = new Date()
tomorrow.setDate(today.getDate() + 1);

Method 2

You can achieve this by using momentjs

let momentObject = moment('Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time)')
momentObject.add(1,'days');

Then to finally get your date object

let dateToBeSet = momentObject.toDate();

then you can use this dateToBeSet object to do whatever you want

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply