Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert String to a Date object

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading