Converting UTC string to epoch time in javascript

时光毁灭记忆、已成空白 提交于 2019-11-28 10:14:41

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})-(\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

Using datejs will help you convert the UTC string to a Date object. After that it's simply a matter of calling .getTime() on the date object to get the milliseconds.

this is how to do it. No nonsese. Date.UTC accepts a UTC timestamp and returns epoch

var epoch_date = Date.UTC(year,mon,day,hours,min,sec,milisec);

You could use getDateFromFormat(dateValue, dateFormat) (available here) like so:

getDateFromFormat("2011-03-29 17:06:21","yyyy-MM-dd HH:mm:ss")

It returns the epoch time in milliseconds.

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:

Math.floor(new Date('2011-03-29 17:06:21 UTC') / 1000); // => 1301418381
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!