3

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.

Zong
  • 6,160
  • 5
  • 32
  • 46
mgeraci
  • 33
  • 3
  • 2
    http://momentjs.com/ – Christian Bonato Apr 21 '16 at 00:13
  • 4
    Your time string does not have time zone information, so JavaScript assumes it's UTC (GMT). When you call `.getHours()` it gives you the hours in *your* local time zone. If you were to call `getUTCHours()` you'd get 19. – Pointy Apr 21 '16 at 00:15
  • Possible duplicate of [How to ISO 8601 format a Date with Timezone Offset in JavaScript?](http://stackoverflow.com/questions/17415579/how-to-iso-8601-format-a-date-with-timezone-offset-in-javascript) – Steven Moseley Apr 21 '16 at 00:48
  • getUTCHours still gets transformed to client side timezone – conor909 Jan 20 '23 at 10:33

1 Answers1

3

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
Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55