时间戳转日期字符串
function unixToStr(num) {
let d = new Date(Number(num) * 1000);
return `${d.getFullYear()}年${(d.getMonth() + 1)}月${(d.getDate())}日 ${d.getHours()}时${d.getMinutes()}分${(d.getSeconds())}秒`;
}
讲解
函数的参数是时间戳数字,单位是秒。因为JavaScript时间戳单位是1/1000秒,所以第二行需要对参数乘以1000。
在该函数使用了JavaScript的字符串模板,整个函数的代码极其简洁。
日期字符串转时间戳
function strToUnix(dateString) {
let d = new Date();
let date = String(dateString);
let year = parseInt(date); // 获取年
if (isNaN(year) || year < 1000 || year > 3000) {
return Number.NaN;
}
let index = date.indexOf("年");
let month = index === -1 ? Number.NaN : parseInt(date.substring(index + 1)) - 1; // 获取月
if (isNaN(month) || month < 0 || month > 11) {
return Number.NaN;
}
index = date.indexOf("月");
let day = index === -1 ? Number.NaN : parseInt(date.substring(index + 1)); // 获取日
if (isNaN(day) || day < 1 || day > 31) {
return Number.NaN;
}
index = date.indexOf("日");
let hour = index === date.length - 1 ? 0 : parseInt(date.substring(index + 1)); // 获取时,获取失败时值为0
if (hour < 0 || hour > 23) {
return Number.NaN;
}
index = date.indexOf("时");
let min = index === -1 ? 0 : parseInt(date.substring(index + 1)); // 获取分,获取失败时值为0
if (min < 0 || min > 59) {
return Number.NaN;
}
index = date.indexOf("分");
let sec = index === -1 ? 0 : parseInt(date.substring(index + 1)); // 获取秒,获取失败时值为0
if (sec < 0 || sec > 59) {
return Number.NaN;
}
d.setFullYear(year); // 设置年
d.setMonth(month); // 设置月
d.setDate(day); // 设置日
d.setHours(hour); // 设置时
d.setMinutes(min); // 设置分
d.setSeconds(sec); // 设置秒
return 0 | d.getTime() / 1000;// 返回时间戳,精度是秒,0或运算是为了保证返回的是整数而不是浮点数
}
讲解
函数的参数是日期型字符串,可以对类似"2013年4月5日6时7分8秒"和""2013年4月5日"两种字符串日期格式进行处理,转成时间戳。对于年月日三个关键字严格匹配,若年月日匹配失败会返回NaN。对于时分秒进行了处理,若时分秒匹配失败会将时分秒分别将其设为0。