Issue
In my Javascript application, I want to convert a string to an actual Date object.
My string is something like this; '2023-06-16 09-25-41'
Then I convert it to a Date with a desired format using moment.js library;
const dateStr = moment('2023-06-16 09-25-41', 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
return new Date(dateStr);
which gives output; Fri Jun 16 2023 09:25:41 GMT+0300 (GMT+03:00)
The problem is that I want this date to be in UTC instead of GMT+03:00, so that it will still be 09:25:41 when I process this in my backend application. But I'm getting 06:25:41 instead right now.
So my question is, how can I convert my string to a Date object while keeping it in UTC.
Solution
You can get the time and add the offset, add the two and pass the result to a Date
constructor.
const dateStr = moment('2023-06-16 09-25-41', 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
let date = new Date(dateStr);
console.log(new Date(date.getTime() - date.getTimezoneOffset() * 60000));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Answered By - Lajos Arpad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.