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.
2
Answers
You have to use
.utc()
method inmoment.js
. Also, you can usetoDate()
instead of the additionalDate()
constructor.Also
If you just start to use
moment.js
in your project, Please find some modern alternatives like Date-fns. Here is why?You can get the time and add the offset, add the two and pass the result to a
Date
constructor.