时间类工具函数总结

日期格式转换

方式1

function doubleFormat (num){
  return num >= 10 ? num : '0' + num
}
function parse2Date (time){
  if (time instanceof Date) return time;
  if (time === undefined) return new Date();
  let str = typeof time === 'number' ? time
    : !isNaN(+time) ? +time
    : String(time).replace(/(\d+)-(\d+)-(\d+)\s+/g, '$1/$2/$3 ');
  return new Date(str);
}
function timeFormatter(time,format='yyyy-MM-dd hh:mm') {
  time = parse2Date(time);
  window.test = time
  let result = format;
  result = result.replace('yyyy',()=>{
    return time.getFullYear()
  })
  result = result.replace('MM',()=>{
    return doubleFormat(time.getMonth() + 1)
  })
  result = result.replace('dd',()=>{
    return doubleFormat(time.getDate())
  })
  result = result.replace('hh',()=>{
    return doubleFormat(time.getHours())
  })
  result = result.replace('mm',()=>{
    return doubleFormat(time.getMinutes())
  })
  result = result.replace('ss',()=>{
    return doubleFormat(time.getMinutes())
  })
  return result
}
timeFormat(new Date()) // 2018-11-12 11:06:05

方式2

function zeller(date) {
    const c = parseInt(date.getFullYear() / 100, 10);
    let y = parseInt(date.getFullYear() % 100, 10);
    let m = parseInt(date.getMonth() + 1, 10);
    const d = parseInt(date.getDate(), 10);
    let w = 0;
    if (m === 1 || m === 2) { // 判断月份是否为1或2
      y -= 1;
      m += 12; // 某年的1、2月要看作上一年的13、14月来计算
    }
    w += y + parseInt(y / 4, 10);
    w += parseInt(c / 4, 10) - (2 * c);
    w += parseInt((13 * (m + 1)) / 5, 10);
    w += (d - 1); // 蔡勒公式的公式
    while (w < 0) w += 7; // 确保余数为正
    w %= 7;
    return Math.ceil(w);
  };
function timeFormat(date, fmt = 'yyyy-MM-dd hh:mm:ss w') { 
    let rnFmt = fmt;
    const o = {
      'M+': `${date.getMonth() + 1}`, // 月份
      'd+': `${date.getDate()}`, //
      'h+': `${date.getHours()}`, // 小时
      'm+': `${date.getMinutes()}`, //
      's+': `${date.getSeconds()}`, //
      'w+': ['日', '一', '二', '三', '四', '五', '六'][zeller(date)],
      // 'q+': Math.floor((mt.getMonth() + 3) / 3), // 季度
      // 'S': mt.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(rnFmt)) {
      rnFmt = rnFmt.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
    }
    Object.keys(o).forEach(k => {
      if (new RegExp(`(${k})`).test(rnFmt)) {
        rnFmt = rnFmt.replace(
          RegExp.$1,
          (RegExp.$1.length === 1) ? o[k] : ((`00${o[k]}`).substr(o[k].length)),
        );
      }
    });
    return rnFmt;
  };
timeFormat(new Date()) // 2018-11-12 11:06:05 一

注意:RegExp.$n是非标准的,尽量不要在生产环境中使用。 
【RegExp.$n】(n为1-9之间的数值)指的是与正则表达式匹配的第n个 子匹配(以括号为标志)字符串。 
【RegExp.$_】与正则表达式匹配的完整字符串。
posted @ 2018-11-12 11:09  maomao^_^  阅读(129)  评论(0编辑  收藏  举报