Using AngularJS date filter with UTC date

后端 未结 10 2265
無奈伤痛
無奈伤痛 2020-11-28 07:35

I have an UTC date in milliseconds which I am passing to Angular\'s date filter for human formatting.

{{someDate | date:\'d MMMM yyyy\'}}

A

10条回答
  •  爱一瞬间的悲伤
    2020-11-28 07:39

    Here is a filter that will take a date string OR javascript Date() object. It uses Moment.js and can apply any Moment.js transform function, such as the popular 'fromNow'

    angular.module('myModule').filter('moment', function () {
      return function (input, momentFn /*, param1, param2, ...param n */) {
        var args = Array.prototype.slice.call(arguments, 2),
            momentObj = moment(input);
        return momentObj[momentFn].apply(momentObj, args);
      };
    });
    

    So...

    {{ anyDateObjectOrString | moment: 'format': 'MMM DD, YYYY' }}
    

    would display Nov 11, 2014

    {{ anyDateObjectOrString | moment: 'fromNow' }}
    

    would display 10 minutes ago

    If you need to call multiple moment functions, you can chain them. This converts to UTC and then formats...

    {{ someDate | moment: 'utc' | moment: 'format': 'MMM DD, YYYY' }}
    

提交回复
热议问题