How to convert date in RFC 3339 to the javascript date object(milliseconds since 1970)

Google calendar throws at me rfc3339, but all my dates are in those milliseconds since jan 1970.

rfc3999:

2012-07-04T18:10:00.000+09:00

javascript current time: (new Date()).getTime():

1341346502585

I prefer the the milliseconds because I only deal in countdowns and not in dates.

Answers:

Answer

Date.parse should work:

Date.parse('2012-07-04T18:10:00.000+09:00')

However, Date.parse is notoriously unreliable across browsers, so you'll want to test it thoroughly. If it doesn't work, then here's a function:

var googleDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})([+-]\d{2}):(\d{2})$/;

function parseGoogleDate(d) {
    var m = googleDate.exec(d);
    var year   = +m[1];
    var month  = +m[2];
    var day    = +m[3];
    var hour   = +m[4];
    var minute = +m[5];
    var second = +m[6];
    var msec   = +m[7];
    var tzHour = +m[8];
    var tzMin  = +m[9];
    var tzOffset = new Date().getTimezoneOffset() + tzHour * 60 + tzMin;

    return new Date(year, month - 1, day, hour, minute - tzOffset, second, msec);
}
Answer

There are two Javascript date libraries that you could try:

Both of these will give you functions that allow you to parse and generate dates in pretty much any format.

If you're working with dates a lot, you'll want to use use one of these libraries; it's a whole lot less hassle than rolling your own functions every time.

Hope that helps.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.