skip to Main Content

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


  1. You have to use .utc() method in moment.js. Also, you can use toDate() instead of the additional Date() constructor.

    const date = moment('2023-06-16 09-25-41', 'YYYY-MM-DD HH:mm:ss')
                      .utc()
                      .toDate(); 
    

    Also
    If you just start to use moment.js in your project, Please find some modern alternatives like Date-fns. Here is why?

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search