4

Js时间与时间戳的相互转换

 1 year ago
source link: https://www.fly63.com/article/detial/12280
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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时间戳:

语言毫秒
JavaScriptMath.round(new Date() / 1000)new Date().getTime()
JavaSystem.currentTimeMillis() / 1000System.currentTimeMillis()
Pythonint(time.time())int(time.time() * 1000)
Gotime.Now().Unix()time.Now().UnixNano() / 1e6
phptime()(int)(microtime(true) * 1000)
RubyTime.now.to_i(Time.now.to_f * 1000).to_i
C#DateTimeOffset.UtcNow.ToUnixTimeSeconds()DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
SwiftNSDate().timeIntervalSince1970NSDate().timeIntervalSince1970 * 1000
Objective-C[[NSDate date] timeIntervalSince1970][[NSDate date] timeIntervalSince1970] * 1000

在线转换工具

这是一款在线将时间和时间戳相互转换的工具。

地址:https://www.fly63.com/tool/etc/#?id=4

链接: https://www.fly63.com/article/detial/12280


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK