Home > Software engineering >  How to format a string in UTC to the configured timezone on Moment
How to format a string in UTC to the configured timezone on Moment

Time:03-02

I have the following string, which is in UTC:

2022-02-01T00:00:00Z

I have already configured my timezone, so I do not want to mess/call .tz()

I know that this string is in UTC, but I am not managing to convert from UTC to the defined timezone, which in this example is pacific/wallis.

I have tried many things, as

const utc = moment.utc('2022-02-01T00:00:00Z').toDate()
const inConfiguredTimeZone = utc.format()

My desire is to get this timestamp 2022-02-01T00:00:00Z and have converted to the defined timezone on Moment

I need to tell moment that "This string is in UTC, please give me the converted timestamp in the defined time zone"

CodePudding user response:

If you just want to format a UTC timestamp in your current timezone (determined by your computer's time settings) just use

let s = moment("2022-02-01T00:00:00Z").format();

This will produce a string like 2022-02-01T12:00:00 12:00 if you are currently in a timezone that has a UTC offset of 12 hours (like pacific/wallis) or 2022-02-01T01:00:00 01:00 if you are currently in a timezone that has a UTC offset of 1 hours (like europe/berlin)

If you want it converted to a specific timezone use

let s = moment("2022-02-01T00:00:00Z").tz("pacific/wallis").format();

This will produce 2022-02-01T12:00:00 12:00, regardless of your current timezone.

  • Related