Search code examples
timezonemomentjsmoment-timezone

Getting datetime as a string in current timezone


In the MySQL DB: '2020-04-19 22:00:00'(UTC). That's also what my endpoint returns since I set the connection option dataStrings:true.

On the client, after I fetch date:

const timezone = moment.tz.guess();

const convertedDate = moment(date)
   .tz(timezone)
   .format();

convertedDate then equals to "2020-04-19T22:00:00+02:00" (I'm in the UTC+2 zone).

I would like to get it in the format "2020-04-20T00:00:00" instead. How can I do that?


Solution

  • It looks like moment(date) believes your incoming date value is in local time, not UTC. So, your timezone conversion to local time changes nothing. You can tell moment it's UTC, like this:

    const timezone = moment.tz.guess();
    
    const convertedDate = moment.utc(date)
       .tz(timezone)
       .format();