Javascript将人类时间转换为时间戳 [英] Javascript Converting human time to timestamp

查看:130
本文介绍了Javascript将人类时间转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript,如何将人造时间字符串(例如Wed Jun 20 19:20:44 +0000 2012)转换为时间戳记值,如1338821992?

Using javascript, How can I convert a "human time" string like "Wed Jun 20 19:20:44 +0000 2012" into a timestamp value like "1338821992"?

推荐答案

只需创建一个 Date 对象,并执行 .getTime() 或使用 Date.parse()

Just create a Date object from it and do .getTime() or use Date.parse():

var d = new Date("Wed Jun 20 19:20:44 +0000 2012");
d.getTime(); //returns 1340220044000

//OR

Date.parse("Wed Jun 20 19:20:44 +0000 2012"); //returns 1340220044000

如果您的人造时间字符串的格式为Date构造函数了解(您发布的示例)。

Works great if your "human time" string is in a format that the Date constructor understands (which the example you posted is).

编辑

实现你可能意味着一个Unix时间戳,它是从时代开始的秒数(不像ms时间戳的ms)。在这种情况下,只需将JS时间戳划分为 1000

Realized you may mean a Unix timestamp, which is seconds passed since the epoch (not ms like JS timestamps). In that case simply divide the JS timestamp by 1000:

//if you want to truncate ms instead of rounding just use Math.floor()
Math.round(Date.parse("Wed Jun 20 19:20:44 +0000 2012") / 1000); //returns 1340220044

这篇关于Javascript将人类时间转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆