获取当前时间戳ts(13位)
let ts=new Date().getTime();
将时间戳ts转换为日期
var date = new Date(ts);
//date就是对应的日期对象,可以取年份,日期等等各种参数
函数
function ts_to_time(timestamp) {
if(typeof timestamp ==='string'){
timestamp=Number(timestamp);
}
if(typeof timestamp !=='number') {
alert("输入参数无法识别为时间戳");
}
let date = new Date(timestamp);
let Y = date.getFullYear() + '-';
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
let D = date.getDate() + ' ';
let h = date.getHours() + ':';
let m = date.getMinutes() + ':';
let s = date.getSeconds();
return Y + M + D + h + m + s;
}
将日期字符串str转换为时间戳ts
let ts = new Date(str).getTime();
注意日期字符串的格式:
console.log(new Date()); | 正确 |
console.log(new Date('2021/11/19')); | 正确 |
console.log(new Date('2021-11-19')); | 正确 |
console.log(new Date(2021,11,19)); | 正确 |
console.log(new Date('2021-11-19 12:12:12')); | 正确 |
console.log(new Date('2021/11/19 12:12:12')); | 正确 |
console.log(new Date(2021,11,19,12,12,12)); | 正确 |
console.log(new Date('20211119121212')); | 错误 |