js将timestamp对象与时间字符串之间的转换

时间:2022-05-28 17:50:00

 

1. 时间戳转日期字符串

var timestamp = timestampObj.time;获取时间戳的毫秒数
var d = new Date(timestamp); //根据时间戳生成的时间对象
var date = (d.getFullYear()) + "-" +
(d.getMonth() + 1) + "-" +
(d.getDate()) + " " +
(d.getHours()) + ":" +
(d.getMinutes()) + ":" +
(d.getSeconds());

console.log(date);

2. 日期字符串转时间戳

var date = '2015-03-05 17:59:00.0';
date = date.substring(0,19);    
date = date.replace(/-/g,'/'); 
var timestamp = new Date(date).getTime();
document.write(timestamp);

3. 当前时间换时间戳
var timestamp = parseInt(new Date().getTime()/1000);    // 当前时间戳
document.write(timestamp);