Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 796
user1184100 Avatar asked May 14 '15 11:05

user1184100


People also ask

What is the format of date () in angular?

The date filter formats a date to a specified format. By default, the format is "MMM d, y" (Jan 5, 2016).

What does new date () return in angular?

What is new Date () in angular? new Date(datestring): It creates a new date object from a date string. 4. new Date ( year, month, date[, hour, minute, second, millisecond ]): It creates a new date object with a specified date and time.


2 Answers

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

like image 126
scniro Avatar answered Sep 22 '22 11:09

scniro


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

like image 25
Sergiu Paraschiv Avatar answered Sep 18 '22 11:09

Sergiu Paraschiv