user1184100
user1184100

Reputation: 6894

Date issue in angular

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

Upvotes: 10

Views: 10360

Answers (3)

scniro
scniro

Reputation: 16979

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

Upvotes: 8

kazimt9
kazimt9

Reputation: 563

{{dateModel | date : 'yyyy-MM-dd'}}
// {{ date_expression | date : format : timezone}}

Upvotes: 1

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

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

Upvotes: 1

Related Questions