日期和时间格式化

2020-02-26  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读