废话不多说,直接上代码:
/**
* 时间格式化
* @param date 字符串或日期类型
* @param fmt yyyy-MM-dd hh:mm:ss
* @returns {*}
*/
function formatDate(date, fmt){
date=date || new Date();
fmt=fmt || 'yyyy-MM-dd hh:mm:ss';
if(Object.prototype.toString.call(date).slice(8,-1)!=='Date'){
date=new Date(date)
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}
function padLeftZero (str) {
return ('00' + str).substr(str.length)
}
//测试用例
console.log(formatDate());
console.log(formatDate(new Date('2017-02-02')));
console.log(formatDate(new Date(2017,2,2)));
console.log(formatDate(new Date("2017/02/02")));
console.log(formatDate(new Date('2017-02-02'),'yyyy-MM-dd hh:mm'));
console.log(formatDate('2017-02-02','yyyy-MM-dd hh'));
结果如图:
结果解释:
- 对于new Date(‘2017-02-02’)的结果:在ES5之中,如果日期采用连词线(-)格式分隔,且具有前导0,JavaScript会认为这是一个ISO格式的日期字符串,导致返回的时间是以UTC时区计算的。于是假设用户处于格林尼治国际标准时的时区,所以返回8点0分。
- 对于new Date(2017,2,2),如果不需要+8小时,用这个
- 对于new Date(2017,2,2)的结果:月份从0开始,所以结果是3月份