Format Date time in AngularJS

后端 未结 13 1743
Happy的楠姐
Happy的楠姐 2020-11-30 22:00

How do I properly display the date and time in AngularJS?

The output below shows both the input and the output, with and without the AngularJS date filter:



        
相关标签:
13条回答
  • 2020-11-30 22:58

    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' }}
    

    https://gist.github.com/cmmartin/341b017194bac09ffa1a

    0 讨论(0)
提交回复
热议问题