Javascript 将人类时间转换为时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11172568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:45:47  来源:igfitidea点击:

Javascript Converting human time to timestamp

javascriptdate

提问by HandiworkNYC.com

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"?

使用javascript,如何将“Wed Jun 20 19:20:44 +0000 2012”等“人类时间”字符串转换为“1338821992”等时间戳值?

回答by Chad

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

只需Date从中创建一个对象并执行.getTime()或使用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

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

如果您的“人类时间”字符串采用 Date 构造函数可以理解的格式(您发布的示例就是这种格式),则效果很好。



EDIT

编辑

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:

意识到您可能指的是 Unix 时间戳,它是自纪元以来经过的秒数(而不是像 JS 时间戳那样的毫秒)。在这种情况下,只需将 JS 时间戳除以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

回答by Niet the Dark Absol

In theory, with Date.parse(). In practice, however, with the thousands of different ways to express date and time (the least of which being the names of days/months in different languages), it's far easier to get the date in its component parts instead of trying to read a string.

理论上,与Date.parse(). 然而,在实践中,由于有成千上万种不同的方式来表示日期和时间(其中最少的是不同语言的天/月的名称),在其组成部分中获取日期要容易得多,而不是试图阅读一个细绳。

回答by Brandon Boone

Looks like the date/time you've provided is in seconds not milliseconds. So you'll need to divide by 1000 to get the date/time in seconds.

看起来您提供的日期/时间是以秒为单位而不是毫秒。因此,您需要除以 1000 才能获得以秒为单位的日期/时间。

//Gets date in seconds 
var d1 = Date.parse('Wed Jun 20 19:20:44 +0000 2012')/1000;
alert(d1);

Example: http://jsfiddle.net/AUt9K/

示例:http: //jsfiddle.net/AUt9K/

回答by GB Patil

Simply add following: new Date().getTime()

只需添加以下内容: new Date().getTime()

This should get you timestamp of current time. Example: var url = "http://abc.xyz.com/my-script.js?v=" + new Date().getTime();

这应该为您提供当前时间的时间戳。例子: var url = "http://abc.xyz.com/my-script.js?v=" + new Date().getTime();