15

I have a mongoose connection to a database containing Date objects in a collection. I want to view these Date objects using Angular Material's DatePicker control. The Date object follow the ISO string format.

Here is a code snippet:

<md-datepicker 
     ng-model="license.expirationdate" md-placeholder="Enter date">
</md-datepicker>    

I get the following error:

The ng-model for md-datepicker must be a Date instance.

When researching, I found that you can use filters to create a Date instance but this did not work for me -> I got an error message saying that the model value is non-assignable when using a simple filters. The filter simply returned a new Date object based on the string input.

How can I format the strings to Date objects while still allowing for ng-model changes?

EDIT: schema for mongoose var Schema = mongoose.Schema;

var Schema = mongoose.Schema;

var modelschema = new Schema({
    name : String,
    licensetype : String,
    activationcount : Number,
    expirationdate: Date,
    key : String
})

here is the express routing which populates the schema

app.post('/licenses', function (req, res) {

    console.log(req.body.expirationDate);
    License.create({

        name: req.body.licenseName,
        licensetype: req.body.licenseType,
        activationcount: 0,
        expirationdate: req.body.expirationDate,
        key: "123456"
    }, function (err, license) {

        if (err) {
            res.send(err);
            console.log(err);
        }

        //Send user back to main page
        res.writeHead(301, {
            'Location': '/',
            'Content-Type': 'text/plain'
        });
        res.end();
    }
    )

});
4
  • What does license.expirationdate look like? Commented Dec 14, 2015 at 18:40
  • It is set using the same DatePicker control and gives the following result: 2015-12-15T23:00:00.000Z Commented Dec 14, 2015 at 18:45
  • Ok can you show the code where you are populating license.expirationdate or even just licsense please? In what way you do you want the model to change - like is new date going to come in and you want it to re-populate the datepicker? do you want to change the date and send it back out or what? Commented Dec 14, 2015 at 19:06
  • expirationdate is populated by simply sending the DatePicker's output to mongoose schema with the expirationdate type being Date. I want the DatePicker to properly view the Date stored in the database and I would like to use the ng-changed event to update the database when I change the date on the DatePicker. Commented Dec 14, 2015 at 19:44

6 Answers 6

16

Here is an example:

Markup:

<div ng-controller="MyCtrl">
    <md-datepicker ng-model="dt" md-placeholder="Enter date" ng-change="license.expirationdate = dt.toISOString()">
    </md-datepicker>
    {{license.expirationdate}}
</div>

JavaScript:

app.controller('MyCtrl', function($scope) {

    $scope.license = {
        expirationdate: '2015-12-15T23:00:00.000Z'
    };

    $scope.dt = new Date($scope.license.expirationdate);

});

Fiddle: http://jsfiddle.net/masa671/jm6y12un/

UPDATE:

With ng-repeat:

Markup:

<div ng-controller="MyCtrl">
    <div ng-repeat="d in data">
        <md-datepicker
            ng-model="dataMod[$index].dt"
            md-placeholder="Enter date"
            ng-change="d.license.expirationdate = dataMod[$index].dt.toISOString()">
        </md-datepicker>
        {{d.license.expirationdate}}
    </div>
</div>

JavaScript:

app.controller('MyCtrl', function($scope) {
    var i;

    $scope.data = [ 
        { license:
            { expirationdate: '2015-12-15T23:00:00.000Z' }
        },
        { license:
            { expirationdate: '2015-12-20T23:00:00.000Z' }
        },
        { license:
            { expirationdate: '2015-12-25T23:00:00.000Z' }
        }
    ];

    $scope.dataMod = [];
    for (i = 0; i < $scope.data.length; i += 1) {
        $scope.dataMod.push({
            dt: new Date($scope.data[i].license.expirationdate)
        });
    }
});

Fiddle: http://jsfiddle.net/masa671/bmqpyu8g/

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your example. This clarifies a lot. How would I create the date instances if I populate a table using ng-repeat and a collection?
10

You can use ng-init, a custom filter, and ng-change and accomplish this in markup.

JavaScript:

app.filter('toDate', function() {
    return function(input) {
        return new Date(input);
    }
})

HTML:

<md-datepicker
     ng-init="date = (license.expirationdate | toDate)"
     ng-model="date"
     ng-change="license.expirationdate = date.toISOString()"
     md-placeholder="Enter date">
</md-datepicker>

With this approach, you don't need to clutter your Controller code with View logic. The drawback is that any programmatic changes to license.expirationdate in the Controller will not be reflected in the View automatically.

1 Comment

Thanks so much, we were trying to avoid messing with the controller code. <3
8

http://jsfiddle.net/katfby9L/1/

// Configure the $httpProvider by adding our date transformer
app.config(["$httpProvider", function ($httpProvider) {
    $httpProvider.defaults.transformResponse.push(function(responseData){
        convertDateStringsToDates(responseData);
        return responseData;
    });
}]);

var regexIso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;

function convertDateStringsToDates(input) {
    // Ignore things that aren't objects.
    if (typeof input !== "object") return input;

    for (var key in input) {
        if (!input.hasOwnProperty(key)) continue;

        var value = input[key];
        var match;
        // Check for string properties which look like dates.
        // TODO: Improve this regex to better match ISO 8601 date strings.
        if (typeof value === "string" && (match = value.match(regexIso8601))) {
            // Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
            var milliseconds = Date.parse(match[0]);
            if (!isNaN(milliseconds)) {
                input[key] = new Date(milliseconds);
            }
        } else if (typeof value === "object") {
            // Recurse into object
            convertDateStringsToDates(value);
        }
    }
}

This will automatically convert all strings in server JSON responses to date

1 Comment

This is brilliant. Saves a lot of the headache of looping through the response data.
6

I would do it like this:

Html:

<div ng-controller="MyCtrl">
    <div ng-repeat="d in data">
        <md-datepicker
            ng-init="date = StrToDate(d.license.expirationdate);"
            ng-model="date"
            md-placeholder="Enter date"
            ng-change="d.license.expirationdate = date.toISOString()">
        </md-datepicker>
        {{d.license.expirationdate}}
    </div>
</div>

In your controller

$scope.StrToDate = function (str) {
            return new Date(str);
        }

Comments

1

I had to make a default date of 6 months from the current day back...

After quite lengthy experiments with date conversion to ISO format and back, I created a simple solution that I did not find here.

The general idea: Take time today and add / subtract time in milliseconds until the required date.

html:

<div flex-gt-xs>
   <h4 class="md-title">Date From:</h4>
      <md-datepicker ng-model="vm.sixMonthBeforeNow" md-placeholder="Date From:"></md-datepicker>
      {{vm.sixMonthBeforeNow}}
</div>

controller:

vm.sixMonthBeforeNow = new Date((+new Date) - 15778800000); // today - 6 month in ISO format (native for Angular Material Datepicker)

result: enter image description here

Maybe it will be useful for someone...

Comments

0

I created a custom directive to handle this for me. I have used the Date class from Sugarjs.com in order for it to work as I have implemented it. This method ensures the date always gets displayed like a date and doesn't jump around with UTC offset involved. You can change the formatter to return new Date(input) if you don't want to confine to UTC.

angular.module 'app.components'
 .directive 'autoChangeStringDates', ->
   directive =
     restrict: 'A'
     require: 'ngModel'
     priority: 2000
     link: (scope, el, attrs, ngModelController) ->
       ngModelController.$formatters.push((input) ->
         if typeof input == Date
          return input
         else
           return Date.create(input, {fromUTC: true})
       )
    return

You then use it in your HTML markup like so

<md-datepicker ng-model='myModel' auto-change-string-dates></md-datepicker>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.