每次写时间转化问题都好痛苦,花费巨大时间理清关系后,下次再写又忘了。好记性不如烂笔头,记录下来,方便下次翻阅。
1.中国标准时间转换为标准年月日时分秒的调用方法如下
export function formatDate(date, fmt) {if(!date){return '';}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;};
2.中国标准时间转换为年月日当天的凌晨00:00:00,具体调用方法如下
const time = new Date();
console.log(time)//输出结果 : Wed Jan 12 11:01:17 GMT+0800 (中国标准时间)
const end = formatDate(new Date(), "yyyy-MM-dd 00:00:00");
console.log(end)//输出结果 :-01-12 00:00:00
3.中国标准时间转换为年月日当天的23:59:59,具体调用方法如下
const time = new Date();
console.log(time)//输出结果 : Wed Jan 12 11:01:17 GMT+0800 (中国标准时间)
const end = formatDate(new Date(), "yyyy-MM-dd 23:59:59");
console.log(end)//输出结果 :-01-12 23:59:59
4.中国标准时间转换为年月日时分秒,具体调用方法如下
const time = new Date();
console.log(time)//输出结果 : Wed Jan 12 11:01:17 GMT+0800 (中国标准时间)
const end = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
console.log(end)//输出结果 :-01-12 11:01:17