Hubert Kubiak
Hubert Kubiak

Reputation: 645

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?

Upvotes: 0

Views: 904

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241920

From your comment in the question:

I'm in the Quatar timezone. The above code returns '2000-01-01T04:00:00' for me ...

This would only happen under one of the following conditions:

  • Regardless of location, you are actually converting from UTC to Qatar's time zone:

    moment("2000-01-01T01:00:00Z").tz('Asia/Qatar').format('YYYY-MM-DDTHH:mm:ss')
    //=> "2000-01-01T04:00:00"
    
  • You are in Qatar, and were just converting to local time:

    moment("2000-01-01T01:00:00Z").format('YYYY-MM-DDTHH:mm:ss')
    //=> "2000-01-01T04:00:00"
    
  • You have loaded the scripts for moment and moment-timezone, but you have not loaded any time zone data. In this case, you will get an error message in the debug console stating Moment Timezone has no data for <zone name> ...

    In this case, the time zone conversion cannot happen, and thus it behaves the same as the code in the previous condition above.

    Instead of loading moment.timzone.js, use one of the files that includes time zone data, such as moment-timezone-with-data-10-year-range.js. See these docs.

I suspect it's the last one.

Upvotes: 1

Tristan De Oliveira
Tristan De Oliveira

Reputation: 808

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 ?

Upvotes: 1

Related Questions