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

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

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

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

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

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

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

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

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

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

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

其它

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

补充:js时间戳转时间

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

new Date(52) 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(35) //'2022/1/18 上午10:09 '

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

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

或者利用正则:

function  getLocalTime(n){    return new Date(parseInt(n)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); } getLocalTime  (35)  //'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(35) //'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(35) //'2022-1-18 10:09:06'

到此这篇关于js/javascript获取时间戳的5种方法的文章就介绍到这了,更多相关js获取时间戳内容请搜索本网站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本网站!

您可能感兴趣的文章:

  • JS如何将当前日期或指定日期转时间戳
  • JS时间戳转换为常用时间格式的三种方式
  • JavaScript 实现日期时间转时间戳
  • JS获取当前时间戳方法解析
  • js时间戳与日期格式之间相互转换
  • JavaScript时间戳与时间日期间相互转换
  • nodejs如何获取时间戳与时间差
  • javascript时间戳和日期字符串相互转换代码(超简单)
  • js时间戳转为日期格式的方法
  • JS获取指定时间的时间戳的方法汇总(最新整理收藏版)