0

Say I have time for a given Olson/tz database timezone, for example, July 1st, 1973 at 15h 23min in Africa/Maputo.

How can I convert it to universal time UT and vice-versa in node.js? I have seen some libraries online, but the documentation is unclear. A complete code example is welcome.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

1 Answers1

1

Using moment.js with moment-timezone, and assuming ISO8601 formatting (you didn't specify).

Loading for node.js

(web browsers can skip this step)

npm install moment-timezone
var moment = require('moment-timezone');

Converting from local time to UTC

var m = moment.tz("1973-07-01T15:23", "Africa/Maputo");
var s = m.toISOString();  // "1973-07-01T13:23:00.000Z"

or

var m = moment.tz("1973-07-01T15:23", "Africa/Maputo");
var s = m.utc().format();  // "1973-07-01T13:23:00.000+00:00"

The first form is more compact and is easiest if you are just sending the result over an API or saving it in a database. The second form is an example of using the utc function, which is more useful if you intend to pass a parameter to format to produce a string formatted differently, or if you intend to call some other function than format.

Converting from UTC to local time

var m = moment.utc("1973-07-01T13:23").tz("Africa/Maputo");
var s = m.format();  // "1973-07-01T15:23:00+02:00"

or

var m = moment("1973-07-01T13:23:00.000Z").tz("Africa/Maputo");
var s = m.format();  // "1973-07-01T15:23:00+02:00"

In the first form, I show that you can use the moment.utc function to parse a string that does not contain offset information and have it interpreted as UTC. This is the more explicit form.

The second form shows that when there is offset information (either Z or +00:00 forms) it is taken into account. Though the intermediate result is a moment object in local mode, the underlying timestamp is still UTC-based, and thus the conversion to the specified time zone still gives the same output.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575