8

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?

Sandeep
  • 1,504
  • 7
  • 22
  • 32
katsuya
  • 1,204
  • 3
  • 16
  • 21

5 Answers5

6

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
maerics
  • 151,642
  • 46
  • 269
  • 291
  • +1 for elegance, but the Date.parse returns NaN on Safari 4.1. Works fine on Firefox 3.6. – Vik David Apr 15 '11 at 21:20
  • 2
    @Vik David: thanks for the heads-up re Safari; I updated my answer to use the UTC method as defined in ECMA-262 5th Edition, which should be better supported. Date parsing sure is a pain in JavaScript... – maerics Apr 15 '11 at 22:01
2

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);
rashid
  • 306
  • 3
  • 12
1

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
Steve Goossens
  • 968
  • 1
  • 8
  • 16
1

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.

steve_c
  • 6,235
  • 4
  • 32
  • 42
  • How would you exactly do this? I have included date.js lib and tried new Date("2011-03-29 17:06:21 UTC") and Date.parse("2011-03-29 17:06:21 UTC") but they returned invalid or NaN. – katsuya Apr 15 '11 at 17:19
0

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.

Vik David
  • 3,640
  • 4
  • 21
  • 29