Recently, when practicing or writing projects, I often encounter the problem of time format conversion. Today I will summarize it.
1. Convert the date to the specified format ( yyyy-MM-dd hh:mm:ss and other formats)
Encapsulation method format
//date指的是new Date(),fmt是格式化的格式
format=(date,fmt)=>{
var o = {
"M+" : date.getMonth()+1, //月份
"d+" : date.getDate(), //日
"h+" : date.getHours(), //小时
"m+" : date.getMinutes(), //分
"s+" : date.getSeconds(), //秒
"q+" : Math.floor((date.getMonth()+3)/3), //季度
"S" : date.getMilliseconds() //毫秒
};
//(y+)匹配多个y,比如yyyy
if(/(y+)/.test(fmt)) {
// RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串
fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
console.log(format(new Date(),'yyyy/MM/dd'))//2022/09/03
console.log(format(new Date(),'yyyy/MM/dd hh:mm:ss'))//2022/09/03 16:11:41
console.log(format(new Date(),'mm:ss'))//18:28
You can also directly add the format method to the Date prototype
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
//使用
console.log(new Date().format("yyyy:MM:dd")//2022:09:03
2. Convert the timestamp to the format of year, month and day
//时间戳转换为yyyy-MM-dd hh:mm:ss
//timestamp(秒为单位)时间戳
export function format(timestamp) {
var date = new Date(timestamp * 1000);
var Y = date.getFullYear() + "-";
var M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
var D =
(date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
var h =
(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
var m =
(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
":";
var s =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}
Or use it in conjunction with format after getting the date
3. Convert time to timestamp
var date = new Date('2022-9-03');
//方式一,得到的是毫秒
var time1 = date.getTime();
//方式二,得到的是毫秒
var time2 = date.valueOf();
Note: Unix timestamps are the number of seconds since January 1, 1970 (midnight UTC/GMT)