new时间对象的时候可以将时间戳传传进去,获取某个时间的时间对象
var date = new Date(); // 日期对象
console.log(dateStr(date.getTime()));
//获取时间戳 然后输出日期字符串 2019-09-20 18:10:54
function dateStr(timestamp){
var date = new Date(timestamp);
return date.getFullYear()
+"-"+((date.getMonth()+1) < 10 ? "0" + (date.getMonth()+1) : (date.getMonth()+1))
+"-"+(date.getDate() < 10 ? "0" + date.getDate() : date.getDate())
+" "+(date.getHours() < 10 ? "0" + date.getHours() : date.getHours())
+":"+(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())
+":"+(date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds())
}
24 * 60 * 60 * 1000 为一天的时间戳
var timestamp = new Date().getTime() // 2019-09-20 18:10:54
dateStr(timestamp - 24 * 60 * 60 * 1000) // 2019-09-29 18:10:54
本文介绍了一种使用JavaScript将时间戳转换为日期字符串的方法。通过创建Date对象并使用自定义函数dateStr,能够准确地将毫秒级时间戳转换为指定格式的日期时间字符串,例如2019-09-20 18:10:54。此外,还演示了如何计算一天的时间戳,并展示了一天前的日期。
130

被折叠的 条评论
为什么被折叠?



