Search code examples
timezonemomentjsmoment-timezoneluxon

Moment Display Date according to ISO-8601 Timezone Offset


I am getting a ISO-8601 date string from an API response as follows :

var x1 = 2022-06-22T05:30:00+05:30

or it could be

var x2 = 2022-06-22T08:30:00-05:00

Irrespective of browser timezone I should display the dates as

X1 - 2022-06-22 05:30:30 IST
X2 - 2022-06-22 08:30:00 EST

How can i parse timezone from the offset like -05:00 or +05:30 using moment or luxon?

I tried moment.tz(timestamp) but it defaults to UTC since it needs the second argument.


Solution

  • So i did a bit more digging.

    Logically what i want is not possible.

    Many timezones shares UTC offset. Hence, there could be ambiguity, if we try to convert an offset to a TimeZone without any other additional info

    Hence, I am opting for a solution, where my API response sends a timezone metadata for each date/time field. (I have lat/long info to convert in Tz in my backend)

    In front End, i will simply use the timezone info to format my moment object into a desired date-time String. For example

    const timestring =  '2022-06-22T00:00:00+00:00'; 
    const timezoneName = "America/Chicago" ;
    moment.tz(timestring, timezoneName).format('YYYY-DD-MM hh:mm:ss z'); 
    // Output: 2022-06-21 07:00:00 CDT
    

    Source : https://stackoverflow.com/tags/timezone/info