Angular http method changing the hour in datetime

1.5k views Asked by At

I have the weirdest bug ever. I am talking to my API via angularjs and I try to update something by doing the following

  console.log('updated: ', event.startsAt);
  $http({
    method: 'PUT',
    url: baseurl + "/event/" +  event.id,
    data: {title: event.title, startsAt: moment(event.startsAt).clone().toDate(), entriesAllowed: event.entriesAllowed},
    headers: {'Content-type': 'application/json'},
    handleError: true
  })

So the problem is in the event.startsAt variable. In the console log it give me the correct time:

Sat Dec 24 2016 16:15:00 GMT+0100 (CET)

but as soon as I send it and access it with my api it gives the same datetime but minus 1 hours so

Sat Dec 24 2016 15:15:00 GMT+0100 (CET)

Any idea what this could be? I use laravel for my api and I am getting the datetime with

$event->startsAt = Carbon::parse($request->get('startsAt'), 'Europe/Amsterdam');

Things I have tried myself

  • Use momentJS to change datetime to a different format.
  • adding/removing timezone in Laravel.
2

There are 2 answers

1
Matt Johnson-Pint On BEST ANSWER

Assuming event.startsAt is a Date object, then you should probably serialize it to ISO8601 format first.

Try event.startsAt.toISOString() first. That will also convert to UTC, but you should be able to handle that easily on the server.

If for some reason you need the original time zone offset persisted, moment can help with that using moment(event.startsAt).format()

1
virth On

Is your API running on the same machine as your angular app? If not you should maybe check the system time of that machine.

Otherwise you should just try the same request with postman to isolate the bug. If the bug is still there with postman you have a problem on your api, if the bug is gone with postman you have a problem with angular. Alltough I can hardly imagine what you could do wrong on the angular side.

Edit:

Just had another idea. try console.log(moment(event.startsAt).clone().toDate()) to really log the thing you send to your server. Maybe the "toDate()" gets it wrong cause of missing timezone information.