Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
DoTheEvo Avatar asked Jul 03 '12 20:07

DoTheEvo


People also ask

How do you parse a date to milliseconds?

Approach : First declare variable time and store the milliseconds of current date using new date() for current date and getTime() Method for return it in milliseconds since 1 January 1970. Convert time into date object and store it into new variable date. Convert the date object's contents into a string using date.

What year since when does JavaScript store dates as a number of milliseconds?

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

What is ISO date format in JavaScript?

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.


1 Answers

Datetimes in that format, with 3 decimal places and a “T”, have well-defined behaviour when passed to Date.parse or the Date constructor:

console.log(Date.parse('2012-07-04T18:10:00.000+09:00'));
// 1341393000000 on all conforming engines

You have to be careful to always provide inputs that conform to the JavaScript specification, though, or you might unknowingly be falling back on implementation-defined parsing, which, being implementation-defined, isn’t reliable across browsers and environments. For those other formats, there are options like manual parsing with regular expressions:

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 = tzHour * 60 + tzMin;

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

console.log(parseGoogleDate('2012-07-04T18:10:00.000+09:00'));

or full-featured libraries like Moment.js.

like image 132
Ry- Avatar answered Sep 18 '22 08:09

Ry-