md-datepicker sending the day before the one that I select
Hello
I've seen closed issue https://github.com/angular/material/issues/4636 named « md-datepicker sending the day before the one that I select ».
@jadjoubran, @jelbourn and @altsel, maybe I have an other solution closer of https://material.angularjs.org/1.0.9/api/service/$mdDateLocaleProvider. Maybe it's better than @altsel solution (11 Nov 2015) , because it uses $mdDateLocaleProvider.formatDate
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
if (!m.isValid()) {
return '';
}
var dateView = moment(date).format('X'), // return unix timestamp of `date' argument
dateCurrentScript = moment().format('X'); // return current unix timestamp
if (dateView + 1 > dateCurrentScript )
return '';
else
return m.format('L');
};
What do you think about that (maybe my code is totally stupid, (sorry)) ?
If you think this solution is good, maybe we can add it in https://github.com/angular/material/issues/4636 ? But for that, we must ask to @ThomasBurleson or an other AngularMaterial collaborator to unlock https://github.com/angular/material/issues/4636 conversation.
Julio
After a while scratching my head i have found the root cause of this and #4636 (and may be others)
TLDR :
- angular-material changes date time to midnight when a date have no time set but it is still using regular javascript Date type.
- regular javascript Date type include your timezone in the time part
It is your job to do a .toLocaleString() to get the right output.
IMHO, if material uses regular js Date type, it should behaves like the regular Date type, or at least users should be informed.
Detailled explanation :
The related code is in the CalendarCtrl from mdCalendar :
/**
* Handles a click event on a date cell.
* Created here so that every cell can use the same function instance.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.cellClickHandler = function() {
var cellElement = this;
if (this.hasAttribute('data-timestamp')) {
$scope.$apply(function() {
var timestamp = Number(cellElement.getAttribute('data-timestamp'));
self.setNgModelValue(self.dateUtil.createDateAtMidnight(timestamp));
});
}
};
When the user select a date in the calendar, a Date object is created because the datepicker model is a Date.
But, the Date object is modified, the time part is set to 0,0,0,0 in createDateAtMidnight.
Now we know this, let's explain something.
In ES5 (don't know what is the behavior in others versions), when you create a Date with just YYYY-MM-DD pattern, javascript include your timezone in the time part.
For example :
var testDate = new Date('2016-07-27');
Will output to :
Wed Jul 27 2016 02:00:00 GMT+0200 (Paris, Madrid (heure d’été))
So, the angular material datepicker tweaks the classical javascript Date behavior.
I think it should not even i think the js behavior is very weird.
moment.js do the same thing, but it is not an angular-material dependency, so angular-material users cannot know that material is tweaking the classical javascript behavior and it leads to HUGE headscratching.
Let's give an example :
I am in Paris, so GMT+2.
My backends returns mainly YYYY-MM-DD date format when the time is not needed.
When i process backend data in promises, i do something like that :
// serviceModel is where my data are stored in the app
// data is the data returned by $http promise
serviceModel.date = new Date(data.date);
I am in GMT+2, so serviceModel.date equals : Wed Jul 27 2016 02:00:00 GMT+0200 (Paris, Madrid (heure d’été))
Now, i publish serviceModel.date in a view, serviceModel.date becomes ng-model for a md-datepicker.
User changes the date to 30/07/2016 (french format).
serviceModel.date is now Mon Jul 30 2016 00:00:00 GMT+0200 (Paris, Madrid (heure d’été)).
If you bind that value directly to the view you will get "2016-07-29T22:00:00.000Z"
Others output :
date.toDateString()=Mon Jul 30 2016date.toGMTString()=Sun, 29 Jul 2016 22:00:00 GMTdate.toISOString()=2016-07-29T22:00:00.000Zdate.toLocaleDateString()=30/07/2016date.toLocaleString()=30/07/2016 à 00:00:00
FYI, with #9410 you should be able to specify your time zone via ng-model-options. E.g. if you set ng-model-options="{ timezone: 'utc' } the time will always be set to 00:00.
Here is my solution, this is a form parser that returns new object with parsed momentJs
const getUTCDate = (date: Date): Date => {
const utcDate = new Date(date.getTime());
utcDate.setHours(0, -date.getTimezoneOffset(), 0, 0);
return utcDate;
};
// momentToDate gets object, that has values some instances of Moment and parses them to UTC date
const momentToDate(objInput: Object): Object => {
return Object.keys(objInput).reduce((acc: Object, key: string): Object => {
if (objInput[key] instanceof Date) {
return { ...acc, [key]: objInput[key] };
}
if (Array.isArray(objInput[key])) {
return {
...acc, [key]: objInput[key].map(x => this.momentToDate(x))
};
}
if (isMoment(objInput[key])) {
console.log(objInput[key]);
console.log(getUTCDate(objInput[key].toDate()));
return { ...acc, [key]: getUTCDate(objInput[key].toDate()) };
}
if (typeof (objInput[key]) === 'object' && objInput[key] !== null) {
return { ...acc, [key]: this.momentToDate(objInput[key]) };
}
return { ...acc, [key]: objInput[key] };
}, {});
}
It might need some modification depending on your required I/O