js中的时间格式化

  • js的时间格式化和根据标准时间格式获得时间。
    • opt可以根据需要改写。
var dateTime = {
  /**
   * 根据标准时间格式(yyyy-MM-dd HH:mm:ss)获得时间
   */
  getDateByFormat: function (dateStr) {
    dateStr = dateStr.replace('-', '/');
    return new Date(Date.parse(dateStr));
  },
  /**
   * 根据模板获得时间的格式化
   */
  dateFormat: function (date, formatStr) {
    // 转换成Date类型
    var date = new Date(date);
    var opt = {
      'yyyy': date.getFullYear(),
      'MM': addZero(date.getMonth() + 1),
      'M': date.getMonth() + 1,
      'dd': addZero(date.getDate()),
      'd': date.getDate(),
      'HH': addZero(date.getHours()),
      'H': date.getHours(),
      'mm': addZero(date.getMinutes()),
      'm': date.getMinutes(),
      'ss': addZero(date.getSeconds()),
      's': date.getSeconds()
    };

    // 如果是个位数则前面添加0
    function addZero(value) {
      return value < 10 ? '0' + value : value;
    }

    // 遍历替换
    for (var k in opt) {
      formatStr = formatStr.replace(k, opt[k]);
    }
    return formatStr;
  },
  /**
   * 标准时间格式
   */
  formatPattern: 'yyyy-MM-dd HH:mm:ss'
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值