Reputation: 318
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.date + ' ' + req.body.time);
const userTz = req.body.tz;
const offset = moment.tz(userTz).utcOffset();
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):
2016-09-06T11:41:00Z
Thanks in advance!
Upvotes: 0
Views: 1163
Reputation: 15566
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 moment.tz
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.date+ " " + req.body.time,"MM/DD/YYYY HH:mm:ss" ,req.body.tz)
.utc()
.format();
console.log(a);
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data-2010-2020.min.js"></script>
Upvotes: 3