I have a date string for example '2022-03-08 04:41:00', which I want to use to create a new Date() and I require output as '2022-03-08T04:41:00.000Z', but I get '2022-03-07T23:11:00.000Z' where it adds offset hours while creating a new Date object.
How do I get the required output format with keeping offset while parsing and creating a new date Object?
CodePudding user response:
I take it you are having problems with timezones. If you have a date like "1/12/2020 04:41:00", you will (most likely) run into problems with timezones (the date parsing function (I presume Date()), will automatically use the current timezone when parsing the date).
A simple solution would be to include the timezone. Something like "Sun Feb 20 2022 05:23:58 Coordinated Universal Time" would work well with most every run of Date().
CodePudding user response:
The one simple way I found to solve this is by removing offset hours and set new hours for the created Date object.
let date= new Date(dateString)
switch(timeZone){
case 'CST': {
date.setHours(date.getHours()-6)
return date;
}
case 'EST': {
date.setHours(date.getHours()-5)
return date;
}
case 'MST': {
date.setHours(date.getHours()-7)
return date;
}
case 'PST': {
date.setHours(date.getHours()-8)
return date;
}
}