Creating the ical file not appending Z for UTC

48 views Asked by At

I have the following code, which is generating the ics file successfully. But I wanted the DTSTART to append with Z at the end as it is UTC, but that is not happening.

  public class IcalGenerator {

    public static void main(String[] args) {

        /* Create the event */
        String eventSummary = "New Year";
        LocalDateTime start = LocalDateTime.now(ZoneId.of("UTC"));
        VEvent event = new VEvent(start, Duration.of(30, ChronoUnit.MINUTES), eventSummary);
        event.add(new Clazz(Clazz.VALUE_PUBLIC));
        event.add(new Description("New meeting"));

        /* Create calendar */
        Calendar icsCalendar = new Calendar();
        var version = new Version();
        version.setValue(Version.VALUE_2_0);
        icsCalendar.add(version);

        // Set the location
        Location location = new Location("Conference Room");

        // Add the Location to the event
        event.add(location);

        /* Add event to calendar */
        icsCalendar.add(event);

        /* Create a file */
        String filePath = "my_meeting.ics";
        FileOutputStream out = null;
        try {

            out = new FileOutputStream(filePath);
            CalendarOutputter outputter = new CalendarOutputter();
            outputter.output(icsCalendar, out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ValidationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

Can you help me what I am missing? I wanted finally DTSTART:20231110T164148Z instead of DTSTART:20231110T164148

When I append manually Z then it works good.

1

There are 1 answers

0
fortuna On

Here are some examples from the ical4j unit tests:

        date                                                | expectedString
    LocalDate.of(2023, 11, 10)                          | 'DTSTART;VALUE=DATE:20231110\r\n'
    LocalDateTime.of(2023, 11, 10, 1, 1, 1)             | 'DTSTART:20231110T010101\r\n'
    LocalDateTime.of(2023, 11, 10, 1, 1, 1)
            .atZone(ZoneId.of('Australia/Melbourne'))   | 'DTSTART;TZID=Australia/Melbourne:20231110T010101\r\n'
    LocalDateTime.of(2023, 11, 10, 1, 1, 1)
            .toInstant(ZoneOffset.UTC)                  | 'DTSTART:20231110T010101Z\r\n'

Currently a LocalDateTime is interpreted as floating time in ical4j, so you need to use Instant to represent UTC.

https://github.com/ical4j/ical4j/blob/674cc6860871f9fe6157a152ad2a4436824ada04/src/test/groovy/net/fortuna/ical4j/model/property/DtStartTestSpec.groovy#L58