js时间格式化
我在开发vue后台项目的时候,订单一个时间格式,预约一个时间格式,发布一个时间格式……
后端传的都是时间戳,而时间戳又有10位和13位混着来。
于是我封装了一个函数:
// 时间格式
date_format(time,data='ymdhms'){
var reg = /^\d{4}-(?:0\d|1[0-2])-(?:[0-2]\d|3[01])( (?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d)?$/;
var str = time;
if (reg.test(str)){
return time;
}
if(time!=null && time!=''){
let dateMat = time
if(String(time).length == 10){
dateMat = new Date(parseInt(String(time).replace("/Date(", "").replace(")/", ""), 10)*1000);
}
if(String(time).length == 13){
dateMat = new Date(parseInt(String(time).replace("/Date(", "").replace(")/", ""), 10));
}
const year = dateMat.getFullYear();
const month = (dateMat.getMonth()+1)<10?'0'+(dateMat.getMonth()+1):(dateMat.getMonth()+1);
const day = dateMat.getDate()<10?'0'+dateMat.getDate():dateMat.getDate();
if(data == 'ymdhms'){
const hh = dateMat.getHours()<10?'0'+dateMat.getHours():dateMat.getHours();
const mm = dateMat.getMinutes()<10?'0'+dateMat.getMinutes():dateMat.getMinutes();
const ss = dateMat.getSeconds()<10?'0'+dateMat.getSeconds():dateMat.getSeconds();
const timeFormat= year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
return timeFormat
}
if(data == 'ymdhm'){
const hh = dateMat.getHours()<10?'0'+dateMat.getHours():dateMat.getHours();
const mm = dateMat.getMinutes()<10?'0'+dateMat.getMinutes():dateMat.getMinutes();
const timeFormat= year + "-" + month + "-" + day + " " + hh + ":" + mm;
return timeFormat
}
if(data == 'ymdh'){
const hh = dateMat.getHours()<10?'0'+dateMat.getHours():dateMat.getHours();
const timeFormat= year + "-" + month + "-" + day + " " + hh;
return timeFormat
}
if(data == 'ymd'){
const timeFormat= year + "-" + month + "-" + day;
return timeFormat
}
}else{
return '无'
}
},
参数一:
可以是时间戳10位或13位,也可以是已经格式化的时间。
为空时返回‘无’
参数二:
参数二的取值可以是自定义的,贴出的函数默认是:
‘ymdhms’:返回年月日时分秒(xxxx-xx-xx xx:xx:xx)。
另外还可填:
‘ymdhm’:返回年月日时分(xxxx-xx-xx xx:xx)。
‘ymdh’:返回年月日时(xxxx-xx-xx xx)。
‘ymd’:返回年月日时(xxxx-xx-xx)。
用法
- 可放在vue minix里调用。
- vue export函数导出
- vue 的过滤器,但需要小小的修改一下
- 原生的话直接用