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.