Home > Mobile >  Date Manipulation in React Native
Date Manipulation in React Native

Time:09-24

myDate = "2021-09-13T00:00:00"

now I try to create a date out of the sting

new Date().setDate(new Date(options.startDate).getDate()) which is "2021-09-13T17:56:08-05:00"

the problem here, somehow it uses my current time with the date, however I want to be able to set the time to either midnight or noon.

I looked at many posts here in Stackoverflow however no solution worked for me.

Any feedback, please?

CodePudding user response:

If you want to parse a date and then change the hours (time) then you can use setHours. This assumes you want to stay in local time.

To explicitly overwrite to an exact time, you can use the overloaded function:

setHours(hoursValue)
setHours(hoursValue, minutesValue)
setHours(hoursValue, minutesValue, secondsValue)
setHours(hoursValue, minutesValue, secondsValue, msValue) <-- this

Snippet:

const myDate = "2021-09-13T00:00:00";

const parsedDate = new Date(myDate);
console.info(parsedDate.toString());

// set to 12pm
parsedDate.setHours(12, 00, 00, 00);
console.info(parsedDate.toString());

// set to midnight, which is essential next day
parsedDate.setHours(24, 00, 00, 00);
console.info(parsedDate.toString());

  • Related