Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - Converting UTC string to epoch time in javascript

How can I convert UTC date-time string (e.g. 2011-03-29 17:06:21 UTC) into Epoch (milliseconds) in javascript?

If this is not possible, is there any way to compare (like <, >) UTC date time strings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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})-(dd)-(dd)s+(dd):(dd):(dd)s+UTCs*$/
    , 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...