Reputation: 33
I'm receiving a time string from an AJAX call to the EventBrite API that looks like: 2016-04-29T19:00:00
I've got a JS function that parses out the month, day, and year just fine, but the getHours()
method is returning 12:00:00
(from the date string above).
Code:
eventStart = data.events[i].start.local; //looping through events array returned by api
startTime = new Date(eventStart);
eventMonth = month[startTime.getMonth()]; // works
eventDay = startTime.getDate(); //works
eventHour = startTime.getHours(); //returns 12:00:00
Any help would be appreciated.
Upvotes: 3
Views: 2610
Reputation: 7270
The problem is most likely stemming from the timezone offset. I'm assuming you're in the Pacific timezone, guessing form the -7h difference. It's attempting to give you a converted UTC timestamp when you call getHours()
, since the timestamp doesn't provide any timezone offset information.
Instead, you can call getUTCHours()
, which will give you the hours without the timezone offset.
var d = new Date('2016-04-29T19:00:00');
d.getHours(); // 12
d.getUTCHours(); // 19
Alternatively, you can include the timezone offset in the date string, which is probably the better choice if you want to allow for some automatic localization.
E.g.
var ds = '2016-04-29T19:00:00';
var d = new Date(ds + '-07:00');
d.getHours(); // 19
d.getUTCHours(); // 2, since UTC is 7 hours ahead, the full date would be 2016-04-30T02:00:00Z
Or more reliably, use getTimezoneOffset
, although this may cause some surprising results if you're using this on a server/client that's not located in the same timezone as the event. (E.g., sever returns time based on UTC-07:00
, client recieves that date, and adds its local timezone offset of UTC-04:00
. This can actually be done by just calling setMinutes()
, and adding the current minutes, and the timezone offset, since JavaScript's date parsing can handle overflowing dates (setting minutes to 300 would automatically roll up the hours as needed).
E.g.
var d = new Date('2016-04-29T19:00:00');
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
d.getHours(); // 19
d.getUTCHours(); // 2
Upvotes: 3