日期和时间格式化

/**
 * @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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。