Search code examples
javascripttimezonemomentjsutc

Convert N hours UTC format to Custom time zone using Moment JS


I have saved attribute in UTC time as N hours (example time: 15), and now i want to convert it back to custom time zone.

I want to use moment js and convert this 15 H from UTC time zone to custom time zone (example: Europe/Berlin)

First i convert from Europe/Berlin to UTC:

hours = 15
moment.tz(hours, "HH", "Europe/Berlin").utc().format("HH")

This is saved as 13 in database. Now i want to convert back 13 hours from UTC to Europe/Berlin.

Custom time zone(Europe/Berlin) is dynamic.

Any help?


Solution

  • You can parse the hours again as UTC, and then set the timezone explicitly to Europe/Berlin before formatting:

    console.log(moment.tz('13', "HH", 'GMT').tz('Europe/Berlin').format("HH"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.17/moment-timezone-with-data.min.js"></script>