js 时间戳和日期格式相互转换
一、时间戳转化为日期格式
这个比较麻烦,没有找到js自带函数进行转换,所以需自定义一个函数,可作为公共函数使用。
使用效果如下:
time = timestampToTime(1660208851);
console.log(time) // 2022-08-11 17:07:31
具体函数:
//将时间戳转换成日期格式
function timestampToTime(timestamp) {
var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘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;
}
二、时间格式转换为时间戳
转换方式
var date = new Date('2022-08-11 17:07:31:122');
//转化为 Thu Aug 11 2022 17:07:31 GMT+0800 (中国标准时间)
// 三种方式获取
var time1 = date.getTime(); //精确到毫秒
var time2 = date.valueOf(); //精确到毫秒
var time3 = Date.parse(date); //精确到秒,毫秒用000代替
console.log(time1);//1660208851122
console.log(time2);//1660208851122
console.log(time3);//1660208851000
var timestamp = time3 / 1000; //除1000得到时间戳
console.log(timestamp); // 1660208851
具体封装函数:
//将时间戳转换成日期格式 datestr实例:'2022-08-11 17:07:31:122'
function dateToTimestamp(datestr) {
var date = new Date(datestr);
var time = Date.parse(date);
var timestamp = time / 1000; //除1000得到时间戳
return timestamp;
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。