Skip to content

Convert to iCalendar (rfc5545)

Philipp Kewisch edited this page May 1, 2024 · 1 revision

Basic Components and Subcomponents

Start off creating the basic data structure and set a property on that:

var comp = new ICAL.Component(['vcalendar', [], []]);
comp.updatePropertyWithValue('prodid', '-//iCal.js Wiki Example');
comp.toString();
// BEGIN:VCALENDAR
// PRODID:-//iCal.js Wiki Example
// END:VCALENDAR

Sub-components are created as needed and attached to the appropriate place in the "tree":

var vevent = new ICAL.Component('vevent'),
    event = new ICAL.Event(vevent);

// Set standard properties
event.summary = 'foo bar';
event.uid = 'abcdef...';
event.startDate = ICAL.Time.now();

// Set custom property
vevent.addPropertyWithValue('x-my-custom-property', 'custom');

// Add the new component
comp.addSubcomponent(vevent);

// Getting the full calendar now
comp.toString();
// BEGIN:VCALENDAR
// PRODID:-//iCal.js Wiki Example
// BEGIN:VEVENT
// SUMMARY:foo bar
// UID:abcdef...
// DTSTART:20161031T122128
// X-MY-CUSTOM-PROPERTY:custom
// END:VEVENT
// END:VCALENDAR

Creating iCalendar from jCal

If you have a jCal object directly, you can stringify it to iCalendar:

var jCal = 
  ["vcalendar",
    [
      ["calscale", {}, "text", "GREGORIAN"],
      ["prodid", {}, "text", "-//Example Inc.//Example Calendar//EN"],
      ["version", {}, "text", "2.0"]
    ],
    [
      ["vevent",
        [
          ["dtstamp", {}, "date-time", "2008-02-05T19:12:24Z"],
          ["dtstart", {}, "date", "2008-10-06"],
          ["summary", {}, "text", "Planning meeting"],
          ["uid", {}, "text", "4088E990AD89CB3DBB484909"]
        ],
        []
      ]
    ]
  ];

ICAL.stringify(jCal);
// BEGIN:VCALENDAR
// CALSCALE:GREGORIAN
// PRODID:-//Example Inc.//Example Calendar//EN
// VERSION:2.0
// BEGIN:VEVENT
// DTSTAMP:20080205T191224Z
// DTSTART;VALUE=DATE:20081006
// SUMMARY:Planning meeting
// UID:4088E990AD89CB3DBB484909
// END:VEVENT
// END:VCALENDAR

Many ICAL classes also have a toJSON() method that will generate jCal or a fragment of it.

Multi-value properties

Here is how to create a multi-value property like EXDATES:

const times = [new ICAL.Time({year: 2020}), new ICAL.Time({year: 2021})];
const vevent = new ICAL.Component('vevent');
const exdate = new ICAL.Property('exdate');
exdate.setValues(times);
vevent.addProperty(exdate);

exdate.toICALString();
//EXDATE;VALUE=DATE:20200101,20210101