广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >javascript获取时间戳的5种方法详解
  • 820
分享到

javascript获取时间戳的5种方法详解

js获取时间戳js时间戳 2023-03-19 17:03:42 820人浏览 独家记忆
摘要

js/javascript获取时间戳的5种方法 1.获取时间戳精确到秒,13位 const timestamp = Date.parse(new Date()); console.l

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'

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

--结束END--

本文标题: javascript获取时间戳的5种方法详解

本文链接: https://www.lsjlt.com/news/200338.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作