Reputation: 363
I was using a angularUI datepicker in my webapp when I suddently came across this:
http://plnkr.co/edit/MLnWCtYHMNqLeuFOetWH?p=preview
In particular I am setting the date in my controller like this:
$scope.getDate = function() {
$scope.dt = new Date(2015,0,1);
};
$scope.getDate();
then in my html I display the date in this two ways:
<pre>With angular date filter date is: <em>{{dt | date:'medium' }}</em></pre>
<pre>Without angular date filter is: <em>{{dt}}</em></pre>
As you can see in this plunker, I have selected the date "01/01/2015" (january 1st, 2015) and if I see the plunker with the Angular date filter I get the correct date and time.
However, if I remove the filter, I get the same date 1 hour in the past.
It is surely a problem of timezones, but I cannot find any sources of this behavior, so I wanted to understand what's going on. Is there any explanation or a website to browse?
Also, what will arrive at the server? Do I have to do some special formatting on the server? (i cannot test this atm)
Don't know if this matters (I think yes), but my browser lives in Italy.
Upvotes: 0
Views: 66
Reputation: 4853
Both displayed dates are the exact same moment. They are just formatted differently. When you instantiate a date, your browser uses your current timezone (1st of January 2015 at midnight in Italy, so UTC+1).
When using a date filter, Angular displays your date in your current timezone whereas it displays the UTC date without.
Just try:
var date = new Date(2015,0,1);
date.toString(); // -> "Thu Jan 01 2015 00:00:00 GMT+0100 (CET)"
date.toISOString(); // -> "2014-12-31T23:00:00.000Z" (Z means UTC time)
As a rule of thumb, always use ISO8601 date format when sending your dates to the server (it is what JSON.stringify does when serializing an object with date values).
Upvotes: 2