10

I'm using HTML5 date picker. After choosing the date the ng-model shows older date rather the current date selected.

<input type="date" ng-model="dateModel" />

When I choose current date ng-model has 2015-05-13T18:30:00.000Z instead of 2015-05-14. If I use in jQuery it stores properly as 2015-05-14

How can I resolve this?

Plunker - AngularJS

Plunker - jQuery

scniro
  • 16,844
  • 8
  • 62
  • 106
user1184100
  • 6,742
  • 29
  • 80
  • 121

3 Answers3

8

This is the correct date for your Angular version, however the date is formatted to UTC which could appear to be wrong if you are not fully aware of this.

The timezone is always zero UTC offset, as denoted by the suffix "Z".

UTC Source

Look into Angular date filters. There are many options out of the box and just about any format you wish can be obtained - but most importantly, resolved to your time zone. For example...

{{dateModel | date:'shortDate'}}  // -- prints 5/14/15
{{dateModel | date:'yyyy-MM-dd'}} // -- prints 2015-05-14

Plunker Link


More about explicitely providing a timezone paramater and trusting the browser to resolve our time (Angular docs)

{{ date_expression | date : format : timezone }}  // -- template binding
$filter('date')(date, format, timezone)           // -- javascript

Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used.


If your preference is to explicitly define a timezone with ngModelOptions rather than leveraging filters, you can do so with the following

<input type="date" 
    ng-model="dateModel" 
    ng-model-options="{timezone: timezone}" /> 


var date = new Date()
$scope.timezone = ((date.getTimezoneOffset() / 60) * -100) // e.g. -400 EDT

See this answer which explains logic behind the manual calculation

Plunker Link - with ng-model-options

Community
  • 1
  • 1
scniro
  • 16,844
  • 8
  • 62
  • 106
1

AngularJS sets the model to the UTC date-time. I think this is the issue you need to check: http://github.com/angular/angular.js/issues/8447

So for my timezone if I set ng-model-options="{timezone: '-0200'}" on the input I get the same date-time as the jQuery version: http://plnkr.co/edit/Qesmucv4aU5Yqu9sxbtp?p=preview

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
  • I did $scope.timezone = d.getTimezoneOffset(); and changed the html to is that all I need to do ? – user1184100 May 14 '15 at 12:32
  • 1
    You'd need to divide `d.getTimezoneOffset()` by 60, because it returns offset in minutes and you need it in hours. This works for me: http://plnkr.co/edit/Qesmucv4aU5Yqu9sxbtp?p=preview – Sergiu Paraschiv May 14 '15 at 13:03
1
{{dateModel | date : 'yyyy-MM-dd'}}
// {{ date_expression | date : format : timezone}}
kazimt9
  • 563
  • 5
  • 11