时间相关方法(格式化)
[parse()] 返回1970年1月1日午夜到指定日期(字符串)的毫秒数。 |
时间戳
Math.round(new Date() / 1000) = 1583999922
const date = new Date(timeStamp * 1000); Thu Mar 12 2020 15:58:42 GMT+0800 (中国标准时间)
1.将时间转换为对应格式
/**
* 将时间转换为对应格式
* @param {number} timeStamp 传入的原始时间戳
* @param {string} format 进行格式化的模板
* @return {string} 返回的格式化后的日期
*/
export function formatDate(timeStamp, format) {
if (!timeStamp || !format) {
return '';
}
const yearPtn = 'yyyy';
const monthPtn = 'MM';
const dayPtn = 'dd';
const hoursPtn = 'hh';
const minutesPtn = 'mm';
const secondsPtn = 'ss';
const millisecondsPtn = 'S';
const date = new Date(timeStamp);
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const milliseconds = date.getMilliseconds();
function _fill_(n) {
return n < 10 ? `0${n}` : n;
}
if (isNaN(year)
|| isNaN(month)
|| isNaN(day)
|| isNaN(hours)
|| isNaN(minutes)
|| isNaN(seconds)
|| isNaN(milliseconds)) {
return '';
}
return format
.replace(yearPtn, year)
.replace(monthPtn, _fill_(month + 1))
.replace(dayPtn, _fill_(day))
.replace(hoursPtn, _fill_(hours))
.replace(minutesPtn, _fill_(minutes))
.replace(secondsPtn, _fill_(seconds))
.replace(millisecondsPtn, milliseconds);
}
const timeFarmated = formatDate(createdTime, 'MM-dd');

浙公网安备 33010602011771号