js常用对时间的处理,字符串转时分秒,毫秒值与年月日互换。
2021-03-25 本文已影响0人
陶菇凉
1.毫秒数转年月日时分秒
toDate(str) {
let times = new Date(str);
let Y = times.getFullYear()
let M = times.getMonth()+1<10?'0'+(times.getMonth()+1):times.getMonth()+1
let D = times.getDate()<10?'0'+(times.getDate()):times.getDate()
let h = times.getHours()<10?'0'+(times.getHours()):times.getHours()
let m = times.getMinutes()<10?'0'+(times.getMinutes()):times.getMinutes()
let s = times.getSeconds()<10?'0'+(times.getSeconds()):times.getSeconds()
return times = Y + "-" + M + "-" +D+' '+h + ":" + m + ":" + s;
//同理需要什么样式就拼接什么字符串
}
2.年月日时分秒转毫秒数
timechange(str){
let date = new Date(str).getTime()
return date
}
3.输入数字转化成 时分秒格式
– eg:时间经过了130S处理为经过了2分10秒
timechange(str) {
let times = str;
let second = parseInt((time % 60).ToString());
let minute = parseInt(((time / 60) % 60).ToString());
let hour = parseInt((time / 60 / 60).ToString());
let sec = second < 10 ? "0" + second.ToString() : second.ToString();
let min = minute < 10 ? "0" + minute.ToString() : minute.ToString();
let hou = hour < 10 ? "0" + hour.ToString() : hour.ToString();
times = hou + ":" + min + ":" + sec;
// times = hou + "时" + min + "分" + sec+'秒';
return times
}
}
4.特殊事件格式2019-01-03T00:18:21.000+0000Z转化成正常格式
function renderTime(date) {
var dateee = new Date(date).toJSON();
return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}