javascript 在javascript中将UTC字符串转换为纪元时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5680025/
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
Converting UTC string to epoch time in javascript
提问by katsuya
How can I convert UTC date-time string (e.g. 2011-03-29 17:06:21 UTC
) into Epoch (milliseconds) in javascript?
如何2011-03-29 17:06:21 UTC
在javascript中将UTC日期时间字符串(例如)转换为纪元(毫秒)?
If this is not possible, is there any way to compare (like <, >) UTC date time strings?
如果这是不可能的,有没有办法比较(如 <、>)UTC 日期时间字符串?
采纳答案by maerics
Note that UTC date strings can be compared lexicographically, like strings, since the higher order values appear leftmost in the string.
请注意,UTC 日期字符串可以按字典顺序进行比较,就像字符串一样,因为高阶值出现在字符串的最左边。
var s1 = '2011-03-29 17:06:21 UTC'
, s2 = '2001-09-09 01:46:40 UTC';
s1 > s2; // => true
s2 > s1; // => false
You can extract the date fields from your example string and return the number of milliseconds by using the Date.UTC
method:
您可以从示例字符串中提取日期字段并使用以下Date.UTC
方法返回毫秒数:
var getEpochMillis = function(dateStr) {
var r = /^\s*(\d{4})-(\d\d)-(\d\d)\s+(\d\d):(\d\d):(\d\d)\s+UTC\s*$/
, m = (""+dateStr).match(r);
return (m) ? Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]) : undefined;
};
getEpochMillis('2011-03-29 17:06:21 UTC'); // => 1301418381000
getEpochMillis('2001-09-09 01:46:40 UTC'); // => 1000000000000
回答by rashid
this is how to do it. No nonsese. Date.UTC accepts a UTC timestamp and returns epoch
这是怎么做的。没有废话。Date.UTC 接受 UTC 时间戳并返回纪元
var epoch_date = Date.UTC(year,mon,day,hours,min,sec,milisec);
回答by steve_c
回答by Vik David
You could use getDateFromFormat(dateValue, dateFormat)
(available here)like so:
您可以像这样使用getDateFromFormat(dateValue, dateFormat)
(在此处可用):
getDateFromFormat("2011-03-29 17:06:21","yyyy-MM-dd HH:mm:ss")
It returns the epoch time in milliseconds.
它以毫秒为单位返回纪元时间。
回答by Steve Goossens
As long as the datetime string is something unambiguous like an ISO8601-ish format (i.e. not MM/DD/YYYY vs DD/MM/YYYY), you can just use the Date constructor to parse it and then Math.floor:
只要日期时间字符串像 ISO8601 格式一样明确(即不是 MM/DD/YYYY 与 DD/MM/YYYY),您就可以使用 Date 构造函数来解析它,然后使用 Math.floor:
Math.floor(new Date('2011-03-29 17:06:21 UTC') / 1000); // => 1301418381