Home > Blockchain >  I have a time and a time zone - no date. How do I convert that time to another time zone?
I have a time and a time zone - no date. How do I convert that time to another time zone?

Time:01-25

From the database I get a time as a string: 13:20:00, I get a time zone: America/New_York and a date as a string 2023-01-2 from a linked table

How do convert that time to America/Los_Angeles (would return 10:20:00) or any other time zone?

I am using the moment.js library.

I tried:

const t     = "2023-01-24 13:20:00"
const tzOut = 'America/New_York'
const tzIn  = "America/Los_Angeles"
const m     = moment(t, "YYYY-MM-DD H:mm:SS").tz(tzIn)
return m.tz(tzOut).format("YYYY-MM-DD H:mm:SS"); 
// Returns "2023-01-24 16:20:00"

And this works, but if I change the time zones around:

const t     = "2023-01-24 13:20:00"
const tzIn  = 'America/New_York'
const tzOut = "America/Los_Angeles"
const m     = moment(t, "YYYY-MM-DD H:mm:SS").tz(tzIn)
return m.tz(tzOut).format("YYYY-MM-DD H:mm:SS"); 
// Returns "2023-01-24 13:20:00", should be "2023-01-24 10:20:00"

I believe this is because I am in the America/Los_Angeles time zone, moment.js is factoring this in and moment(t,"YYYY-MM-DD H:mm:SS").tz(tzIn) is becoming 16:20:00. I want it to become 13:20:00 but in America/New_York time zone.

So it seems I am on the wrong track - how should I be doing this?

Edited to add dates.

CodePudding user response:

The issue is that you're confusing moment.tz() and the .tz() method on a moment object. If you need to parse a date in a specific timezone, use moment.tz() to construct a new moment object like usual, but with an extra parameter that is the timezone. If you need to convert to a different timezone, then use the .tz() method.

In your code, the first time you need use moment.tz(), while the second time you need to use the .tz() method. Change your code to this:

const t     = "2023-01-24 13:20:00"
const tzIn  = 'America/New_York'
const tzOut = "America/Los_Angeles"
const m     = moment.tz(t, "YYYY-MM-DD H:mm:SS", tzIn)
return m.tz(tzOut).format("YYYY-MM-DD H:mm:SS")
  • Related