Search code examples
angularjsangularjs-directivedatefilter

Why isn't my dateFormat working?


I have the following code in AngularJS 1.3.10:

ngModelCtrl.$formatters.unshift(function (modelValue) {
    console.log(modelValue)
    var temp = dateFilter(modelValue, 'yyyy-MM-dd');
    console.log(temp);
    return temp;
});

The result returned is still in the full date format of

Fri Feb 27 2015 14:05:20 GMT-0700 (Mountain Standard Time)

instead of

2014-02-27

Here is a plunker that shows the problem:

http://plnkr.co/edit/pOKtD5hScXsPMHFAeglC?p=preview

Any ideas why it's not working?


Solution

  • I got it working with

    var temp = dateFilter(new Date(modelValue), 'yyyy-MM-dd');
    

    (That said, I don't really know enough about formatters to know if this is a proper solution or if you should be doing something else differently.)

    The reason you are seeing this behaviour is because there is a default formatter that converts its argument to a string, and Angular executes the formatters in reverse order. Because you inserted your formatter at the front, the default formatter had already converted the model value into a string before you saw it. So alternatively you could change unshift to push, or just replace the entire $formatters array with an array containing just your function, and those would both work equivalently. I'm not entirely sure what side effects doing so would have.