WJM
WJM

Reputation: 1191

How to format ng-model string to date for angular material datepicker

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();
    }
    )

});

Upvotes: 15

Views: 36929

Answers (6)

Igor Arkhipenko
Igor Arkhipenko

Reputation: 41

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...

Upvotes: 1

Tyrone Wilson
Tyrone Wilson

Reputation: 4618

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>

Upvotes: 0

Jeffrey Patterson
Jeffrey Patterson

Reputation: 2562

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.

Upvotes: 10

mudin
mudin

Reputation: 2852

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);
        }

Upvotes: 6

Toolkit
Toolkit

Reputation: 11119

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

Upvotes: 8

masa
masa

Reputation: 2800

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/

Upvotes: 16

Related Questions