Js时间与时间戳的相互转换
Js时间转为时间戳
1.Date.now()
用Date.now()可以获得当前的时间戳
Date.now()2.Date.parse()
将字符串或者时间对象直接转换为时间戳
, 但是不推荐这种办法,毫秒级别的数值被转化为000
Date.parse()3.valueOf()
通过valueOf()函数返回指定对象的原始值获得准确的时间戳值:
(new Date()).valueOf()4.getTime()
通过原型方法直接获得时间的毫秒值
new Date().getTime()5.Number()
将时间对象转换为一个number 类型的数值,即时间戳
Number(new Date())js时间戳转时间
使用 new Date(时间戳) 格式转化当前时间,比如:
new Date(1672301066362) //Thu Dec 29 2022 16:04:26 GMT+0800 (中国标准时间)注意:时间戳参数必须是Number 类型,如果是字符串,解析结果:invalid Date。
生成“yyyy-MM-dd hh: mm:ss”格式
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(1672301066362) //'2022-12-29 16:04:26'相关知识
1.当前系统区域设置格式(toLocaleDateString和toLocaleTimeString)
(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString()
//'2022/12/29 16:10:49'2.普通字符串(toDateString和toTimeString)
(new Date()).toDateString() + " " + (new Date()).toTimeString()
//"Thu Dec 29 2022 16:11:02 GMT+0800 (中国标准时间)"3.格林威治标准时间(toGMTString)
(new Date()).toGMTString()
'Thu, 29 Dec 2022 08:11:15 GMT'4.Date对象字符串(toString)
(new Date()).toString()
//"Thu Dec 29 2022 16:11:24 GMT+0800 (中国标准时间)"在编程语言中获取Unix时间戳:
| 语言 | 秒 | 毫秒 |
|---|---|---|
| JavaScript | Math.round(new Date() / 1000) | new Date().getTime() |
| Java | System.currentTimeMillis() / 1000 | System.currentTimeMillis() |
| Python | int(time.time()) | int(time.time() * 1000) |
| Go | time.Now().Unix() | time.Now().UnixNano() / 1e6 |
| php | time() | (int)(microtime(true) * 1000) |
| Ruby | Time.now.to_i | (Time.now.to_f * 1000).to_i |
| C# | DateTimeOffset.UtcNow.ToUnixTimeSeconds() | DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() |
| Swift | NSDate().timeIntervalSince1970 | NSDate().timeIntervalSince1970 * 1000 |
| Objective-C | [[NSDate date] timeIntervalSince1970] | [[NSDate date] timeIntervalSince1970] * 1000 |
在线转换工具
这是一款在线将时间和时间戳相互转换的工具。
地址:https://www.fly63.com/tool/etc/#?id=4
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!