askvity

What is the Date Format for ISO in Java?

Published in Java Date Formatting 2 mins read

The most common ISO date format in Java is yyyy-MM-dd, and the date-time format is yyyy-MM-dd'T'HH:mm:ss.SSSXXX.

Here's a breakdown:

ISO Date Format (yyyy-MM-dd)

This format represents the date in the following structure:

  • yyyy: Four-digit year (e.g., 2023)
  • MM: Two-digit month (01-12)
  • dd: Two-digit day of the month (01-31)

Example: 2023-10-27

ISO Date-Time Format (yyyy-MM-dd'T'HH:mm:ss.SSSXXX)

This format represents the date and time together:

  • yyyy-MM-dd: Same as the ISO date format.
  • 'T': A literal character 'T' separating the date and time components.
  • HH: Two-digit hour (00-23)
  • mm: Two-digit minute (00-59)
  • ss: Two-digit second (00-59)
  • SSS: Three-digit milliseconds (000-999)
  • XXX: Time zone offset (e.g., Z for UTC, +01:00, -08:00)

Example: 2023-10-27T10:30:45.123-05:00

Java and ISO Date/Time Formatting

Java provides built-in classes for handling ISO date and time formats, particularly within the java.time package (introduced in Java 8). You can use DateTimeFormatter to parse and format dates and times according to the ISO standard.

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class ISODateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime now = OffsetDateTime.now();
        String isoFormat = now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        System.out.println("Current ISO Date Time: " + isoFormat); //Example Output: 2023-10-27T15:45:00.123+00:00
    }
}

This example demonstrates how to format an OffsetDateTime object into an ISO-compliant string using DateTimeFormatter.ISO_OFFSET_DATE_TIME. Other predefined formatters exist for different ISO date/time representations.

Summary

Java uses the standard ISO 8601 formats, with yyyy-MM-dd for dates and yyyy-MM-dd'T'HH:mm:ss.SSSXXX for date and time with timezone offset, and offers convenient classes for working with these formats programmatically.

Related Articles