Search code examples
javascriptcalendaricalendar

How to parse calendar file dates with JavaScript?


We need to use JavaScript on the browser to read and parse calendar files (.ics) (also called iCal formats). I wrote a custom function to read these values and then use the JavaScript Date() function to make a data object.

Is any easier and better way to do this? Please look at my function (below), your comments would be welcome.

A typical date value from an .ics file looks like this:

DTSTART:20110914T184000Z

Need to break it apart at the colon, so:

var strData = 'DTSTART:20110914T184000Z'
var x = strData.indexOf(":");
var strVal = strData.slice(x + 1 );

next, call a function that returns a date object:

var dateObj = calenDate(strVal);

//resulting dateObj value: Fri Oct 14 2011 18:40:00 GMT-0400 (Eastern Daylight Time)

Here is the function that parses the date.

function calenDate(icalStr)  {
    // icalStr = '20110914T184000Z'             
    var strYear = icalStr.substr(0,4);
    var strMonth = icalStr.substr(4,2);
    var strDay = icalStr.substr(6,2);
    var strHour = icalStr.substr(9,2);
    var strMin = icalStr.substr(11,2);
    var strSec = icalStr.substr(13,2);

    var oDate =  new Date(strYear,strMonth, strDay, strHour, strMin, strSec)

return oDate;
}

I think something is wrong since it is getting the month wrong.


Solution

  • For some odd reason the month parameter is zero-based (reference).

    Change this line in your function.

    var strMonth = icalStr.substr(4,2);
    

    to this:

    var strMonth = parseInt(icalStr.substr(4,2),10)-1;
    

    See working demo on jsFiddle: http://jsfiddle.net/cTkTQ/