Bob T Bob T - 1 year ago 181
Javascript Question

Moment JS - convert user-submitted date/time/timezone to timezone-independent UTC

In my Node.js app a user submits a date, time, and timezone (separate form fields). Using Moment Timezone, I am trying to save the date adjusted for no offset (timezone independent).

The code below works, but is there a simpler/cleaner way to achieve the same result? Having to multiply the offset by -1 seems hackish:

const userDate = new Date( + ' ' + req.body.time);
const userTz =;

const offset =;
const utc = moment(userDate).utcOffset(-1*offset).format('YYYY-MM-DD[T]HH:mm:ss');

Example Input:

Date: 09/06/2016 (via Bootstrap date picker)
Time: 07:41:00 (via Bootstrap time picker)
Timezone: America/New_York (UTC/GMT -4 hours)

Returns (correctly):


Thanks in advance!

Answer Source

You can use the tz to create a date in user entered timezone, for which there is no direct way in javascript date object. Once you have the date reconstructed with go ahead and convert it to utc, now format it however you want.

Also, check your solution(shown in Question) in a browser running from a different timezone, I am pretty sure that it will give different results.

let req = {};
 req.body = {date: "09/06/2016",
             time: "07:41:00",
             tz: "America/New_York"};

const a = moment
           .tz( " " + req.body.time,"DD/MM/YYYY HH:mm:ss" ,

<script src=""></script>
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download