美文网首页
日期和时间格式化

日期和时间格式化

作者: 简单背包客 | 来源:发表于2020-02-26 12:55 被阅读0次
    /**
     * @param value  需要格式化的值,需为日期格式
     * @param style  参数为日期格式,默认为yyyy-MM-dd hh:mm:ss
     * */
    function format(value, style) {
      if (!value) return '';
      if (!style || !(style = style.toString().trim())) style = 'yyyy-MM-dd hh:mm:ss';
      let getDate = new Date(value);
      let o = {
        'M+': getDate.getMonth() + 1,
        'd+': getDate.getDate(),
        'h+': getDate.getHours(),
        'm+': getDate.getMinutes(),
        's+': getDate.getSeconds(),
        'q+': Math.floor((getDate.getMonth() + 3) / 3),
        'S': getDate.getMilliseconds() //millisecond
      };
      if (/(y+)/.test(style)) style = style.replace(RegExp.$1, getDate.getFullYear().toString().substr(4 - RegExp.$1.length));
      for (let k in o) if (new RegExp('(' + k + ')').test(style)) style = style.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(o[k].toString().length));
      return style;
    }
    
    //用法:
    format(new Date(), 'yyyy-MM-dd hh:mm:ss');  // 2019-06-03 12:10:08
    format(new Date('1992/09/06'), 'yyyy-MM-dd');  // 1991-09-06
    

    相关文章

      网友评论

          本文标题:日期和时间格式化

          本文链接:https://www.haomeiwen.com/subject/nkwmchtx.html