erichardson30
erichardson30

Reputation: 5044

Convert date and time to UTC

I am asking the user to input a date and time into my application. The user will input a time based on the timezone they are in. When I save this date and time to my database I want to convert the time to UTC so that when I query by time (which is done in UTC) I can find the entries.

This is what I've currently done :

var date = new Date();
var dateString = "0" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
//format date
date = moment(dateString, "MM/DD/YYYY HH:mm a");
date = new Date(date).toISOString();

Where time is the time the user enters (ex if I want to schedule something for 11:00am, time = 11:00am)

When this is saved to the database, it looks like : ISODate("2016-05-09T11:00:00Z") which is not correct since that is a EST saved as Zulu time.

How can I convert the time (I am using moment) to be saved as the correct Zulu time?

Upvotes: 0

Views: 34102

Answers (2)

erichardson30
erichardson30

Reputation: 5044

To fix this issue I used the moment-timezone library.

I first set the timezone on the server since it will only be accessed by EST :

moment.tz.setDefault("America/New_York");

Then all I needed to do was set the timezone on the moment object to UTC by :

date = moment(dateString, "MM/DD/YYYY HH:mm a").tz("UTC");

This successfully converts the time from EST to UTC

Upvotes: 0

WonderGrub
WonderGrub

Reputation: 396

One option would be to use Javascript's built-in UTC functions.

JavaScript Date Reference

getUTCDate() - Returns the day of the month, according to universal time (from 1-31)
getUTCDay() - Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()- Returns the year, according to universal time
getUTCHours() - Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() - Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() - Returns the minutes, according to universal time (from 0-59)
getUTCMonth() - Returns the month, according to universal time (from 0-11)
getUTCSeconds() - Returns the seconds, according to universal time (from 0-59)

For example,

new Date('2016-05-09 10:00:00')
    returns Mon May 09 2016 10:00:00 GMT-0400

new Date('2016-05-09 10:00:00').getUTCHours()
    returns 14

UPDATE: Examples (including .toISOString())

If we choose July 4, 2016 @ 8:00 PM Eastern Time (GMT-0400), UTC would be July 5, 2016 @ 00:00 (midnight):

var date = new Date('2016-07-04 20:00:00')
date.getUTCFullYear = 2016
date.getUTCMonth = 6 (0 base)
date.getUTCDate = 5
date.getUTCHours = 0
date.getUTCMinutes = 0

var date = new Date('2016-07-04 20:00:00')
date.toISOString() = "2016-07-05T00:00:00.000Z" (UTC)

Upvotes: 5

Related Questions