jodatimejava-time

How to create an date format for an ics file in the form xxxxxxxZ i.e like this 19960704T120000Z


I am trying to create a datetime for the DTSTAMP field of an ICalendar but I unable to find an example of how to do so. When I look at the specification version 2, I find that this is one format that is acceptable or allowed but I simply cannot find to to create that format. I don't want to use an ICalendar library. In an nutshell, I want the field to look like

DTSTAMP:19960704T120000Z

Solution

  • Declare:

    private static final DateTimeFormatter DTSTAMP_FORMATTER
            = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX")
                    .withZone(ZoneOffset.UTC);
    

    Then do:

        ZonedDateTime zdt = ZonedDateTime.of(1996, 7, 4,
                6, 0, 0, 0, ZoneId.of("America/Mazatlan"));
        String formattedForICalendar = zdt.format(DTSTAMP_FORMATTER);
        System.out.println(formattedForICalendar);
    

    Output is the desired:

    19960704T120000Z

    You asked for a format ending in Z for UTC. The formatter ensures this through two measures: I am using pattern letter X in the format pattern string for UTC offset, and I set UTC as the formatter’s override zone.

    Use java.time for your date and time work. Joda-Time was a good library, but is in maintenance mode and officially replaced by java.time.

    If using Joda-Time

    If you’ve got your date and time as a Joda-Time DateTime, there are two options each with their pro and con:

    1. Convert to java.time.
    2. Format using Joda-Time’s DateTimeFormatter.

    The advantage of converting to java.time is this prepares your code better for migrating further to java.time in the future.

        DateTime jodaDateTime = new DateTime(1996, 4, 7,
                6, 0, DateTimeZone.forID("America/Mazatlan"));
        ZonedDateTime zdt = ZonedDateTime.ofInstant(
                Instant.ofEpochMilli(jodaDateTime.getMillis()),
                ZoneId.of(jodaDateTime.getZone().getID()));
    

    With the resulting ZonedDateTime proceed as above.

    To format your Joda-Time DateTime with Joda-Time:

        DateTimeFormatter formatter
                = ISODateTimeFormat.basicDateTimeNoMillis().withZoneUTC();
        String formattedForICalendar
                = jodaDateTime.toString(formatter);
    

    This gives a string identical to the one we got from java.time above. Contrary to java.time Joda-Time has got a built-in formatter for your desired format, basic ISO 8601 format.

    Links: