在UTC中将UTC字符串转换为时代 [英] Converting UTC string to epoch time in javascript
问题描述
如何在UTC中将UTC日期时间字符串(例如 2011-03-29 17:06:21 UTC
)转换为Epoch(毫秒)?
How can I convert UTC date-time string (e.g. 2011-03-29 17:06:21 UTC
) into Epoch (milliseconds) in javascript?
如果这是不可能的,是否有任何方式来比较(如<,)UTC日期时间字符串?
If this is not possible, is there any way to compare (like <, >) UTC date time strings?
推荐答案
请注意,UTC日期字符串可以按字典顺序比较,如字符串,因为较高的顺序值在字符串中最左边。
Note that UTC date strings can be compared lexicographically, like strings, since the higher order values appear leftmost in the string.
var s1 = '2011-03-29 17:06:21 UTC'
, s2 = '2001-09-09 01:46:40 UTC';
s1 > s2; // => true
s2 > s1; // => false
您可以从示例字符串中提取日期字段,并使用< a href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/UTC =nofollow> Date.UTC
方法:
You can extract the date fields from your example string and return the number of milliseconds by using the Date.UTC
method:
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
这篇关于在UTC中将UTC字符串转换为时代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!