Search code examples
javascriptdatetimetimezonemomentjsmoment-timezone

How to get time changed from utc to the chosen timezone in moment.js?


Let's say I have a date like:

"2000-01-01T01:00:00Z"

It is in the UTC timezone. I want to move the time to the Europe/Copenhagen timezone so that it would be "2000-01-01T02:00:00".

I wanted to use moment-timezone to do it. However the problem is that it always uses my local timezone (which is not the Europe/Copenhagen). I tried multiple ways, for example:

const date = '2000-01-01T01:00:00Z';
return moment(date).tz('Europe/Copenhagen').format('YYYY-MM-DDTHH:mm:ss');

But still the point of reference is my local timezone. I don't want it to use my local timezone at all. How to achieve it?


Solution

  • I tried two options.

    The timezone is represented by the 'Z' at the end of the date

    First one like you:

    moment('2000-01-01T01:00:00Z').tz('Europe/Copenhagen').format('YYYY-MM-DDTHH:mm:ss');
    

    Second one is tricky:

    moment.tz('2000-01-01T01:00:00Z', 'UTC').tz('Europe/Copenhagen').format('YYYY-MM-DDTHH:mm:ss');
    

    I get:

    2000-01-01T02:00:00
    

    With the two options. What's the version of moment are you using ?