Reputation: 173
I am using react date picker and getting the selected time value in the below format
Thu Oct 13 2022 00:00:00 GMT+0530 (India Standard Time)
i need to convert the above string to the below formats
(a) "2022-10-13T00:00:00+05:30" (b) "2022-11-03T18:30:00.000Z" (c) "2022-11-03T18:30:00.000Z"
i was able to achieve the format (b) and (c) using the below code
const dateStr = "Thu Oct 13 2022 00:00:00 GMT+0530"; console.log(new Date(dateStr).toUTCString());
but was not able to get the conversion for (a).also as per the logic the month is 1 month ahead and the date is 21 days ahead of the actual value passed.Any way to resolve this?
Upvotes: 0
Views: 241
Reputation: 7616
The JavaScript Date
object has no function to return the local ISO date format. Here is a function that does that. If the offset is omitted, the browser local time is assumed:
function toLocalISO(date, offset) {
if(offset == null) {
offset = date.getTimezoneOffset(); // browser offset in minutes
}
return new Date(date.getTime() - (offset * 60000)).toISOString().replace(/Z$/, function() {
return (offset > 0 ? '-' : '+') +
('0' + (Math.abs(offset)/60*100))
.replace(/^.*(..)(..)$/, '$1:$2')
.replace(/50$/, '30');
});
}
const date = new Date();
console.log(date.toISOString() + ' <== ISO');
console.log(toLocalISO(date) + ' <== browser local ISO');
let offset = -330; // India offset in minutes
console.log(toLocalISO(date, offset) + ' <== India local ISO');
Output: (for me in California local time)
2022-11-04T21:10:40.969Z <== ISO
2022-11-04T14:10:40.969-07:00 <== browser local ISO
2022-11-05T02:40:40.969+05:30 <== India local ISO
Upvotes: 3