angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

1.3.0 input[date] model is a Date object in local time zone instead of UTC

Open estekhin opened this issue 12 years ago • 43 comments

Please check this plunker for a demonstration.

Assuming the computer time zone is not UTC and the browser supports input[date], select a date from the input[date] dropdown.

The input field will display a date in the localized format, for example "01.08.2014" in my case. My current timezone is GMT+4.

value is

"2014-07-31T20:00:00.000Z"

but expected is either

"2014-07-31T20:00:00.000-0400"

or

"2014-08-01T00:00:00.000Z"

It seems that the code that converts input[date].value into a Date model object first obtains the correct value "2014-07-31T20:00:00.000-0400" but then replaces the correct "-0400" suffix with incorrect "Z", or it is a matter of formatting when the date is formatted as localized but the timezone is not part of the format and instead the "Z" suffix is hardcoded..

The code that converts the string value of the input[date] into a Date model should follow the HTML5 input[type=date] guidelines and convert the value string as if it is the start of the day in the UTC regardless of the current timezone.

estekhin avatar Aug 01 '14 14:08 estekhin

@estekhin - Thanks for reporting this issue. Has this ever worked in a previous version of AngularJS?

petebacondarwin avatar Aug 02 '14 15:08 petebacondarwin

I believe this is a valid issue and can be fixed by changing the following line: https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1048

return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm);

to

return new Date(Date.UTC(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm));

But I am not sure how this would affect the parsing of other date/time inputs. Some investigation is needed.

petebacondarwin avatar Aug 02 '14 16:08 petebacondarwin

I think that angular 1.2 does not provide special handling for input[date], so in 1.2 ngModel returns the original string value.

estekhin avatar Aug 02 '14 16:08 estekhin

the date inputs are not implemented in 1.2 at all, so there is no use backporting any fixes there.

caitp avatar Aug 02 '14 16:08 caitp

@petebacondarwin why simple new Date(string value) can't be used? It correctly parses the string returned from input[date].value and returns a date object.

Check http://plnkr.co/edit/tkAyCBoILXQWvC84U2SV?p=preview for a demo - plain input value and a Date object created from it have correct value, while angular model mis-adjusts time-zone and returns a value which can be off-by-one day.

estekhin avatar Aug 04 '14 06:08 estekhin

Related to this issue - if i am fine with input[date] "as is" with the string model, will i be able to disable special input[date] handling in angular 1.3? Is this being discussed somewhere or should i raise a new issue/feature request for this?

estekhin avatar Aug 04 '14 07:08 estekhin

@estekhin - It would be better if we fixed this but you could create an additional input directive that cleared out the $parsers and adds your own. Something like this:

angular.directive('input', function() {
  return function postLink(scope, element, attrs, ngModel) {
    if ( attrs.type !== 'date' || !ngModel ) { return; }
    ngModel.$parsers = [
      function myDateParser(val) { ... }
    ];
  });
});

petebacondarwin avatar Aug 04 '14 08:08 petebacondarwin

Actually from looking at the createDateParser function it appears that if it already has a Date object then it just returns it. So you can even just add your own date parser to the front of the $parsers array and it will supercede the parsing of the built in input directive.

petebacondarwin avatar Aug 04 '14 08:08 petebacondarwin

@tbosch was involved in the original implementation, perhaps he can have a view on this?

petebacondarwin avatar Aug 04 '14 09:08 petebacondarwin

Playing with the http://plnkr.co/edit/tkAyCBoILXQWvC84U2SV?p=preview in IE11 which allows entering arbitrary text into input[date].

Entering invalid "2014-00-00" as input. The input[date].value is the same invalid string "2014-00-00", and new Date(2014-00-00") returns a object that represents "invalid date". But angular model returns a normal Date object that represents "2013-11-29T20:00:00.000Z". From some point of view it is "correct" if treating "2014-00-00" as "2014-01-01" minus one month and one day, but it is really unexpected when moving from string model to Date model.

Entering invalid "2014-33-98" results in similar results, with input[date].value = "2014-33-98", invalid Date object, and angular model reporting date as "2016-12-06".

I see that input[date] and input[time] was discussed https://github.com/angular/angular.js/pull/5864 and issues linked from it but it is already closed. What would be a proper way to propose changes to handling of all time- and date-related inputs in 1.3?

estekhin avatar Aug 04 '14 10:08 estekhin

Tried to use 1.3 snapshot in the real code and, as expected, got unspoken number of problems due to Date values instead of strings and due to actual date values being off-by-one =).

Please consider these requests/requirements:

  1. fix string-to-date conversion so that the resulting Date correlates with algorithms defined in the html5 spec
  • if the string value is valid, then Date is exact and in UTC
  • if the string value is invalid (including out of range values for month or day), then Date is NaN (or whatever is used to report invalid date).
  1. provide a way to disable special handling (especially converting from string to some object) provided by new input[date] and input[time] directives, so that the ngModel value will remain a string. The mechanism to disable probably can be based on ngModelOptions.

  2. consider using hash/object as a model for input elements, with model.value being the plain string value from the input element, and model.data being the parsed object. This can be considered for any kind of input[type] elements.

At the moment i am using the following hack to force the input[date] ngModel to remain a string:

app.directive( 'input', function() {
    return {
        restrict : 'E',
        require : ['?ngModel'],
        priority : 100,
        link : function( scope, element, attr, ngModel ) {
            if ( attr.type === "date" ) {
                var model = ngModel[0];
                model.$parsers.length = 0;
                model.$parsers.push( ng.identity );
                model.$formatters.length = 0;
                model.$formatters.push( ng.identity );
            }
        }
    };
} );

With that hack in place my code seems to work with 1.3 snapshot without any other problems.

estekhin avatar Aug 05 '14 11:08 estekhin

+1 for requests from previous comment. We develop/maintain several applications based on string ng-model of date/time inputs. To migrate to Angular 1.3 we had to introduce the hack similar to the one from previous comment.

ilplotkin avatar Aug 12 '14 08:08 ilplotkin

Possible solution:

there are a dozen of places inside Angular code where the Date constructor with two or more parameters (new Date(year,month,,,)) is used.

replacing all new Date(year,month,,,) with new Date(Date.UTC(year,month,,,)) results in the correct UTC-based value.

estekhin avatar Aug 13 '14 17:08 estekhin

Seems like I am a bit slow as new Date(Date.UTC()) trick was already suggested by @petebacondarwin

Two additional demos:

1.2.21-based: http://plnkr.co/edit/WdNVxblrBPQPiSNTOIPA?p=preview the model value corresponds to the actual input both for input[date] and input[time]

1.3-based: http://plnkr.co/edit/ja9UjP9rtJanYrJCVxMo?p=preview the model value for input[date] is off by one when the computer timezone is in -HH:MM category. the model value for input[time] is off by timezone offset (and the date part is wrong, should be 1970-01-01)

after some reflection i think that i want two things:

  1. fixed input[date] and input[time] values
  2. an ability to completely disable ALL special handling for ALL text-based input.type values - if HTML spec says the input value is text, i want it as text inside ngModel. In extreme case i would question the utility of special handling at all and even would call it feature creep and suggest to remove all special support for input[date/time/datetime/month/week]

estekhin avatar Aug 14 '14 07:08 estekhin

Hi @estekhin I agree, we should fix the off-by-one problem in the Date parsing as suggested.

And in the case where the browser does not support native input[type=date] we should use the date format of the locale for parsing the date (ngLocale already contains the date format, see e.g. https://github.com/angular/angular.js/blob/master/src/ngLocale/angular-locale_de-be.js#L75).

@estekhin Would that also solve your problem? If this is fixed, would you still want the raw string that the user entered? If yes, when are you then parsing the Date?

tbosch avatar Aug 15 '14 18:08 tbosch

@blesh You said that you started on implementing a generic date parser / serializer based on ngLocale. Do you still have this somewhere?

tbosch avatar Aug 15 '14 18:08 tbosch

@tbosch hi,

in my particular case I am using plain string input[date] value as is as one of the parameters in the GET/POST requests. It works very good in modern browsers which always return a yyyy-MM-dd string (and not so good in old browsers which treat input[date] as input[text] and return whatever the user entered).

assuming that ngModel will be a Date with the proper value, converting it into a string is not a problem.

the off-by-one is the real pain because one has to either replace the parser/formatter to "identity" as in the hack above or to correct the Date using the getTimezoneOffset(). Of course it would be better to fix it in inside angular instead of everyone inventing their own ways to deal with it.

estekhin avatar Aug 15 '14 19:08 estekhin

@tbosch - I can look, but I seriously doubt I still have that sitting around. It was a standalone module I made in a plnkr almost a year ago. The basics of it was it was examining the locale strings and creating Regexps from them, which were then used to test and parse the date strings.

benlesh avatar Aug 15 '14 19:08 benlesh

Wow! I found it... Here's a Gist I pulled from the original Plunker:

https://gist.github.com/blesh/accff2313c7998b65727

benlesh avatar Aug 15 '14 19:08 benlesh

I have no idea what state it's in, but as I recall I had it mostly or partially working at some point. There are definitely better ways to do this if you were to build something into Angular core. Also, it could be leveraged in those date/time related directives I added a while back.

benlesh avatar Aug 15 '14 19:08 benlesh