Skip to content
This repository was archived by the owner on May 29, 2019. It is now read-only.
This repository was archived by the owner on May 29, 2019. It is now read-only.

Angular-UI date picker is in invalid state when given a specified date format while the ng-model has a string value as “yyyy-MM-ddThh:mm:ssZ” #4554

@1002nights

Description

@1002nights

I am getting my date value from Mongoose as "2015-10-08T00:00:00Z" and when this is binded to the angular-ui datepicker, the form filed is shown as "ng-invalid". It seems as though when grabbing the date from the model it comes back as a string when datepicker is searching for a date object. This StackOverflow words the question better than myself and shows the issue.

http://stackoverflow.com/questions/33017677/angular-ui-date-picker-is-in-invalid-state-when-specified-the-date-format-as-d

It also has a solution from user, Chet, I don't know his Github handle but the solution is below

angular.module('test')
.config(['$httpProvider', function ($httpProvider) {

    // ISO 8601 Date Pattern: YYYY-mm-ddThh:MM:ss
    var dateMatchPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;

   var convertDates = function (obj) {
      for (var key in obj) {
         if (!obj.hasOwnProperty(key)) continue;

         var value = obj[key];
         var typeofValue = typeof (value);

         if (typeofValue === 'object') {
            // If it is an object, check within the object for dates.
            convertDates(value);
         } else if (typeofValue === 'string') {
            if (dateMatchPattern.test(value)) {
               obj[key] = new Date(value);
            }
         }
      }
   }

   $httpProvider.defaults.transformResponse.push(function (data) {
      if (typeof (data) === 'object') {
         convertDates(data);
      }

      return data;
   });
}])

I just wanted to report this bug and hopefully help a few more people find the solution as I've spent 2 days trying to figure it out.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions