如何在UTC中将UTC日期时间字符串(例如2011-03-29 17:06:21 UTC)转换为Epoch(毫秒)?
如果这不可能,有没有办法比较(如< ;,>)UTC日期时间字符串?
解决方法
请注意,UTC日期字符串可以按字典顺序进行比较,如字符串,因为较高的顺序值最左侧出现在字符串中.
var s1 = '2011-03-29 17:06:21 UTC',s2 = '2001-09-09 01:46:40 UTC'; s1 > s2; // => true s2 > s1; // => false
您可以从示例字符串中提取日期字段,并使用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