码迷,mamicode.com
首页 > Web开发 > 详细

Angularjs中比较使用的DateFormat库

时间:2016-03-11 18:33:19      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

angular.module(‘newApp‘)
  .factory(‘dateUtil‘, function() {
    var symbolMap = {
      ‘MM‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getMonth();
        }
        return date.getMonth() + 1;
      },
      ‘mm‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getMinutes();
        }
        return date.getMinutes();
      },
      ‘YY‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getFullYear();
        }
        return date.getFullYear();
      },
      ‘ss‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getSeconds();
        }
        return date.getSeconds();
      },
      ‘hh‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getHours();
        }
        return date.getHours();
      },
      ‘dd‘: function(date) {
        if (typeof(date) === ‘string‘) {
          var d = new Date(date);
          return d.getDate();
        }
        return date.getDate();
      }
    };

    function _makeNchar(char, n) {
      var str = [];
      while (n--) {
        str.push(char);
      }
      return str.join(‘‘);
    }

    function alignNumber(num, len, char) {
      num = num + ‘‘;
      if (num.length > len) {
        return num;
      } else {
        return _makeNchar(char, len - num.length) + num;
      }
    }

    function getRelativeDate(offset, date) {
      var relativeDate = new Date(date),
        dateValue = relativeDate.getDate() + offset;
      relativeDate.setDate(dateValue);
      return relativeDate;
    }return {
      format: function(date, fmtStr) {
        if (fmtStr) {
          return fmtStr.replace((/(MM|mm|YY|ss|hh|dd)/g), function(s) {
            return alignNumber(symbolMap[s](date), 2, ‘0‘);
          });
        }
      },
      getRelativeDate: getRelativeDate
    };
  });

 

Angularjs中比较使用的DateFormat库

标签:

原文地址:http://www.cnblogs.com/ccblogs/p/5266489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!