momentjs convert datetime to UTC from another timezone
Very similar to @Matt's answer; but using moment-timezone to convert date-time to UTC (as ISO string):
var momentTz = require('moment-timezone');
var utcDate = momentTz.tz('2021-01-27 14:02:45', "YYYY-MM-DD HH:mm:ss", 'Asia/Kolkata').toISOString();
console.log(utcDate);
// output: '2021-01-27T08:32:45.000Z'
The api I was working with required date-time in UTC & in ISO format
// your inputs
var input = "05/30/2014 11:21:37 AM"
var fmt = "MM/DD/YYYY h:mm:ss A"; // must match the input
var zone = "America/New_York";
// construct a moment object
var m = moment.tz(input, fmt, zone);
// convert it to utc
m.utc();
// format it for output
var s = m.format(fmt) // result: "05/30/2014 3:21:37 PM"
Note that I used the same output format as input format - you could vary that if you like.
You can also do this all in one line if you prefer:
var s = moment.tz(input, fmt, zone).utc().format(fmt);
Additionally, note that I used the Area/Locality format (America/New_York
), instead of the older US/Eastern
style. This should be prefered, as the US/* ones are just there for backwards compatibility purposes.
Also, US/Pacific-New
should never be used. It is now just the same as US/Pacific
, which both just point to America/Los_Angeles
. For more on the history of this, see the tzdb sources.