angularjsdatehtml-input

Angular date problems


Please see the following example: https://plnkr.co/edit/SGa2xy7M2OuFYOVkeuYe?p=preview

<div ng-app="app" ng-controller="MainController">
    <div class="col-sm-3">
        <input ng-model="flight.date" name="date" type="date" placeholder="" class="form-control input-md" required="" max="<% Date | date:'yyyy-MM-dd' %>" ng-change="changeDate()">
    </div>
    <% flight.date | date %>
    <% flight.date | date : medium : PST %>
</div>

I'm in GMT+2 timezone (CEST) and GMT+1 in winter time (CET).

When I select today from the input field (Jun 30 2016) the output Angular produces is UTC time. So it subtracts 2 hours from the actual time. But because we're only selecting the date the time is always 00:00:00.

So subtracting 2 hours from 00:00:00 will result in a date of the day before.

How do I fix that? I tried manually adding the time to that timestamp which works. But then the problem still exists between midnight and 2 AM.

I'm currently using the following workaround:

Since we only need the date I'm just manually setting the time to 6PM so the 1 or 2 hour difference doesn't cause the date to change.

d.setHours('18', '00', '00');

Solution

  • A JavaScript Date instance is always relative to your current location. However, you only want to use the day-part and not the time-part, so what you could do is always use one and the same timezone when inputing and displaying the date. Just choose a timezone, e.g. UTC. You can make sure that the time will be inputted using UTC (instead of the browser's default) by adding that as a model option:

    <input ng-model="flight.date" ng-model-options="{timezone:'UTC'}">
    

    Make sure that you also use that timezone when displaying the date:

    <% flight.date | date:'mediumDate':'UTC' %>
    

    See my fork with this update of your Plunker: https://plnkr.co/edit/LqZv7olKCl12OjDMvicF?p=preview