javascript如何获取时间戳

前端开发   发布日期:2023年09月08日   浏览次数:158

这篇文章主要讲解了“javascript如何获取时间戳”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“javascript如何获取时间戳”吧!

js/javascript获取时间戳的5种方法

1.获取时间戳精确到秒,13位

const timestamp = Date.parse(new Date());
console.log(timestamp);
 
//输出 1591669256000   13位

2.获取时间戳精确到毫秒,13位

const timestamp = Math.round(new Date());
console.log(timestamp);
 
//输出 1591669961203   13位

3.获取时间戳精确到毫秒,13位

const timestamp = (new Date()).valueOf();
console.log(timestamp);
 
//输出 1591670037603   13位
const timestamp = (new Date()).valueOf();
console.log(timestamp);
 
//输出 1591670037603   13位

4.获取时间戳精确到毫秒,13位

const timestamp = new Date().getTime();
console.log(timestamp);
 
//输出 1591670068833   13位

5.获取时间戳精确到毫秒,13位

const timestamp = +new Date();
console.log(timestamp);
 
//输出 1591670099066   13位

其它

在开发的中需要精确到秒的时候,推荐使用 第1种方法,也需要除以1000才行,如果是需要时间戳毫秒的推荐 +new Date() 和 new Date().getTime();

补充:js时间戳转时间

我们可以接用 new Date(时间戳) 格式转化获得当前时间,比如:

new Date(1472048779952)
Wed Aug 24 2016 22:26:19 GMT+0800 (中国标准时间)

注意:时间戳参数必须是Number类型,如果是字符串,解析结果:Invalid Date。

如果后端直接返回时间戳给前端,前端如何转换呢?下面介绍2种实现方式

方法一:生成'2022/1/18 上午10:09 '格式

function getLocalTime(n) {   
   return new Date(parseInt(n)).toLocaleString().replace(/:d{1,2}$/,' ');   
}   
getLocalTime(1642471746435) //'2022/1/18 上午10:09 '

也可以用如下,想取几位就几位,注意,空格也算!

function getLocalTime(n) {   
    return new Date(parseInt(n)).toLocaleString().substr(0,14)
}   
getLocalTime(1642471746435) //'2022/1/18 上午10'

或者利用正则:

function  getLocalTime(n){
   return new Date(parseInt(n)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
getLocalTime  (1642471746435)  //'2022/1/18 上午10:09:06'

方法二:生成'yyyy-MM-dd hh:mm:ss '格式

先转换为data对象,然后利用拼接正则等手段来实现:

function getData(n){
  n=new Date(n)
  return n.toLocaleDateString().replace(///g, "-") + " " + n.toTimeString().substr(0, 8)
}
getData(1642471746435) //'2022-1-18 10:09:06'

不过这样转换在某些浏览器上会出现不理想的效果,因为toLocaleDateString()方法是因浏览器而异的,比如 IE为"2016年8月24日 22:26:19"格式 ;搜狗为"Wednesday, August 24, 2016 22:39:42"

可以通过分别获取时间的年月日进行拼接,这样兼容性更好:

function getData(n) {
  let now = new Date(n),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
getData(1642471746435) //'2022-1-18 10:09:06'

以上就是javascript如何获取时间戳的详细内容,更多关于javascript如何获取时间戳的资料请关注九品源码其它相关文章!