Programming Search⌘K

Standardcore

ISO 8601

Also called ISO 8601 date format, ISO date, ISO timestamp, RFC 3339, RFC 9557, week date, ordinal date, ISO duration, ISO week.

ISO 8601 is the international standard for writing dates, times, durations and intervals as text, such as 2024-07-09T14:30:05+02:00. RFC 3339 is its profile for Internet timestamps.

What it is

ISO 8601 is the international standard for dates and times in text. It "is an international standard covering the worldwide exchange and communication of date and time-related data."1 Its aim is to stop the confusion between local conventions, such as 07/09/2024, which is July 9 in the United States and 7 September in most of Europe. In ISO 8601 that date is 2024-07-09.

The order is fixed: "the greatest temporal term (typically a year) is placed at the left and each successively lesser term is placed to the right of the previous term."1 So the text of two dates in the same form sorts in the order of time. The standard covers calendar dates, week dates, ordinal dates, times of day, offsets from UTC, durations, intervals and repeating intervals. Only numbers and a few letters and signs are allowed. Names such as January and Thursday "are not allowed in interchange representations within the standard."1

Most programs use a smaller profile. RFC 3339 "defines a date and time format for use in Internet protocols that is a profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar."2 RFC 9557 extends that format "for representing additional information, including a time zone."3 JSON APIs, logs and databases use these profiles.

Syntax or structure

Dates. One day has three forms:

Form Extended format Basic format Meaning
Calendar date 2024-12-30 20241230 year, month, day
Week date 2025-W01-1 2025W011 week-numbering year, week, day of the week (Monday is 1)
Ordinal date 2024-365 2024365 year, day of the year

The extended format has separators, and the basic format has none. "The separator used between date values (year, month, week, and day) is the hyphen, while the colon is used as the separator between time values (hours, minutes, and seconds)."1 Reduced precision drops the parts on the right: 2024-07 is July 2024.

Week dates. Week 01 is "the week with the starting year's first Thursday in it (the formal ISO definition)"1. Weeks start on Monday. Thus the week-numbering year can differ from the calendar year near 1 January. "If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year (there is no week 00)."1 And 2024-12-30, a Monday, is in week 1 of 2025.

Times and offsets. A time is hh:mm:ss, with an optional decimal fraction, as in 14:30:05.12. A date and a time join with T. A Z after the time means UTC: "Z is the zone designator for the zero UTC offset."1 Otherwise an offset such as +02:00 or -0400 follows. With no Z and no offset, the text is a local time with no known offset.

Durations and intervals. A duration has the form PnYnMnDTnHnMnS or PnW, so P1Y2M10DT2H30M is 1 year, 2 months, 10 days, 2 hours and 30 minutes. "P is the duration designator (for period) placed at the start of the duration representation."1 An interval joins two parts with /: a start and an end, a start and a duration, or a duration and an end. A repeating interval adds R and a count. The interval P1Y2M10DT2H30M repeated five times from 2008-03-01T13:00:00Z is R5/2008-03-01T13:00:00Z/P1Y2M10DT2H30M1.

RFC 3339. Its grammar takes one form of ISO 8601: a full date, T, a full time with seconds and an offset or Z2:

full-date   = date-fullyear "-" date-month "-" date-mday
partial-time = time-hour ":" time-minute ":" time-second [time-secfrac]
time-offset = "Z" / time-numoffset
full-time   = partial-time time-offset
date-time   = full-date "T" full-time

It has no week dates, ordinal dates, basic format or reduced precision. It allows the second 60 for a leap second. It allows a space for T: "Applications using this syntax may choose, for the sake of readability, to specify a full-date and full-time separated by (say) a space character."2 It also gives a meaning to the offset -00:00, for a time whose UTC is known but whose offset to local time is not. In RFC 3339, Z and +00:00 instead mean that UTC is the preferred reference point2.

RFC 9557. It adds suffixes in brackets after an RFC 3339 timestamp, such as a zone name: 2024-07-09T14:30:05+02:00[Europe/Paris]. The RFC explains why the zone matters: "For example, 2020-01-01T00:00+01:00[Europe/Paris] will let programs add six months to the timestamp while adjusting for summer time (daylight saving time)."3 It also changes the meaning of Z, to align RFC 3339 "with the actual practice of interpreting the offset Z to mean the same as -00:00"3. The reason is that ISO 8601:2000 and later "do not actually allow -00:00"3. Now Z says that the local offset is unknown, and +00:00 still says that UTC is the preferred reference point.

Examples

The Python program below writes one day in the three date forms, in the extended and the basic format. It then reads five texts of one instant: with an offset, with Z, with another offset, in the basic format and as a week date.

from datetime import date, datetime, timedelta, timezone

d = date(2024, 12, 30)
year, week, weekday = d.isocalendar()
print(d.isoformat())                              # calendar date, extended format
print(d.strftime("%Y%m%d"))                       # calendar date, basic format
print(f"{year}-W{week:02d}-{weekday}")            # week date: this Monday is in week 1 of 2025
print(f"{d.year}-{d.timetuple().tm_yday:03d}")    # ordinal date: day 365 of a leap year

t = datetime(2024, 7, 9, 14, 30, 5, tzinfo=timezone(timedelta(hours=2)))
print(t.isoformat())
# Five texts for the same instant: offsets, Z, the basic format and a week date.
for s in ["2024-07-09T14:30:05+02:00", "2024-07-09T12:30:05Z", "2024-07-09T08:30:05-04:00",
          "20240709T123005Z", "2024-W28-2T12:30:05Z"]:
    print(s, datetime.fromisoformat(s) == t)
Output
2024-12-30
20241230
2025-W01-1
2024-365
2024-07-09T14:30:05+02:00
2024-07-09T14:30:05+02:00 True
2024-07-09T12:30:05Z True
2024-07-09T08:30:05-04:00 True
20240709T123005Z True
2024-W28-2T12:30:05Z True

The example files write and read ISO 8601 in each language. They show the week-numbering year of 2024-12-30, the forms that each parser rejects, and the durations where a standard library has them.

PythonGitHub
from datetime import date, datetime, timezone

# fromisoformat reads most ISO 8601 forms, but not reduced precision, ordinal dates or durations.
for s in ["2024-07-09", "2024-07-09 12:30", "2024-07-09T12:30:05.5+05:30", "2024-07", "2024-191", "P1DT2H"]:
    try:
        print(f"{s:28} {datetime.fromisoformat(s).isoformat()}")
    except ValueError:
        print(f"{s:28} ValueError")

t = datetime(2024, 7, 9, 12, 30, 5, 120000, tzinfo=timezone.utc)
print(t.isoformat())
print(t.isoformat(timespec="milliseconds"))
print(date.fromisocalendar(2025, 1, 1), date(2024, 12, 30).isocalendar())
Output
2024-07-09                   2024-07-09T00:00:00
2024-07-09 12:30             2024-07-09T12:30:00
2024-07-09T12:30:05.5+05:30  2024-07-09T12:30:05.500000+05:30
2024-07                      ValueError
2024-191                     ValueError
P1DT2H                       ValueError
2024-07-09T12:30:05.120000+00:00
2024-07-09T12:30:05.120+00:00
2024-12-30 datetime.IsoCalendarDate(year=2025, week=1, weekday=1)
  • Verdict: stdlib. datetime.isoformat() writes the extended format, and fromisoformat() reads most ISO 8601 forms, including the basic format and week dates. It rejects reduced precision such as 2024-07, ordinal dates and durations. It writes +00:00, never Z, for UTC. isocalendar() and fromisocalendar() convert week dates.
#include <chrono>
#include <format>
#include <iostream>

int main() {
    using namespace std::chrono;
    sys_seconds t = sys_days{2024y / 12 / 30} + 12h;
    std::cout << std::format("{:%FT%TZ}", t) << "\n";
    std::cout << std::format("{:%G-W%V-%u}", t) << "\n";
    std::cout << std::format("{:%Y-%j}", t) << "\n";

    // %Ez writes the offset in the extended format, with a colon.
    zoned_time z{"Asia/Kolkata", sys_days{2024y / 7 / 9} + 12h + 30min + 5s};
    std::cout << std::format("{:%FT%T%Ez}", z) << "\n";
}
Output
2024-12-30T12:00:00Z
2025-W01-1
2024-365
2024-07-09T18:00:05+05:30
  • Verdict: stdlib. Since C++20, std::format and std::chrono::parse use the conversions of strftime, plus %Ez for an offset with a colon. The example does not call parse, because libstdc++ added it only in GCC 14 and the test server builds with GCC 13. The library has no parser for ISO 8601 durations.
JavaGitHub
import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate d = LocalDate.of(2024, 12, 30);
        System.out.println(d.format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println(d.format(DateTimeFormatter.BASIC_ISO_DATE));
        System.out.println(d.format(DateTimeFormatter.ISO_WEEK_DATE));
        System.out.println(d.format(DateTimeFormatter.ISO_ORDINAL_DATE));
        // The pattern letter Y is the week-based year. The letter u is the year.
        System.out.println(d.format(DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.ROOT)) + " "
                + d.format(DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT)));

        OffsetDateTime t = OffsetDateTime.parse("2024-07-09T14:30:05+02:00");
        System.out.println(t.toInstant());
        // ZonedDateTime reads and writes a zone name in brackets after the offset.
        System.out.println(ZonedDateTime.parse("2024-07-09T14:30:05+02:00[Europe/Paris]"));
        // Durations: Duration has hours, minutes and seconds, and Period has years, months and days.
        System.out.println(Duration.parse("PT1H30M").toMinutes() + " " + Period.parse("P1Y2M10D"));
    }
}
Output
2024-12-30
20241230
2025-W01-1
2024-365
2025-12-30 2024-12-30
2024-07-09T12:30:05Z
2024-07-09T14:30:05+02:00[Europe/Paris]
90 P1Y2M10D
  • Verdict: stdlib. DateTimeFormatter has constants for the calendar, basic, week and ordinal forms, and toString() of each java.time type writes ISO 8601. Duration and Period parse durations. The pattern YYYY gives the week-based year, which is 2025 for 2024-12-30.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    char buf[64];
    struct tm tm;
    time_t t = 1735560000; /* 2024-12-30T12:00:00Z */
    gmtime_r(&t, &tm);
    const char *formats[] = {
        "%Y-%m-%dT%H:%M:%SZ", /* calendar date and time in UTC */
        "%Y%m%dT%H%M%SZ",     /* the same in the basic format */
        "%G-W%V-%u",          /* week date: %G is the week-numbering year */
        "%Y-%j",              /* ordinal date */
        "%F %T",              /* %F is %Y-%m-%d and %T is %H:%M:%S */
    };
    for (int i = 0; i < 5; i++) {
        strftime(buf, sizeof buf, formats[i], &tm);
        printf("%s\n", buf);
    }

    /* %z writes the offset as +hhmm, the basic format, with no colon. */
    setenv("TZ", "Asia/Kolkata", 1);
    tzset();
    time_t u = 1720528205; /* 2024-07-09T12:30:05Z */
    localtime_r(&u, &tm);
    strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%S%z", &tm);
    printf("%s\n", buf);
    return 0;
}
Output
2024-12-30T12:00:00Z
20241230T120000Z
2025-W01-1
2024-365
2024-12-30 12:00:00
2024-07-09T18:00:05+0530
  • Verdict: stdlib. strftime has the conversions for each part of ISO 8601: %F, %T, %G, %V, %u and %j. Its %z writes the offset in the basic format, so a text in the extended format needs a colon put in by hand. ISO C has no parser; POSIX adds strptime.
using System;
using System.Globalization;
using System.Xml;

var inv = CultureInfo.InvariantCulture;
var t = new DateTimeOffset(2024, 7, 9, 14, 30, 5, 120, TimeSpan.FromHours(2));
// "o" is the round-trip format: ISO 8601 with seven digits of fraction.
Console.WriteLine(t.ToString("o", inv));
Console.WriteLine(t.UtcDateTime.ToString("o", inv));
Console.WriteLine(DateTimeOffset.Parse("2024-07-09T12:30:05.12Z", inv) == t);

// ISOWeek gives the week-numbering year and the week. DayOfWeek counts Sunday as 0.
var d = new DateTime(2024, 12, 30);
Console.WriteLine($"{ISOWeek.GetYear(d)}-W{ISOWeek.GetWeekOfYear(d):00}-{((int)d.DayOfWeek + 6) % 7 + 1}");

// The XML Schema type duration uses the ISO 8601 form.
Console.WriteLine(XmlConvert.ToTimeSpan("PT1H30M"));
Console.WriteLine(XmlConvert.ToString(TimeSpan.FromMinutes(90)));
Output
2024-07-09T14:30:05.1200000+02:00
2024-07-09T12:30:05.1200000Z
True
2025-W01-1
01:30:00
PT1H30M
  • Verdict: stdlib. The format specifier "o" writes ISO 8601, and Parse with the invariant culture reads it. System.Globalization.ISOWeek computes week dates. XmlConvert reads and writes durations in the form of ISO 8601, which XML Schema uses.
JavaScriptGitHub
process.env.TZ = "America/New_York";

// toISOString always writes UTC, with milliseconds and the suffix Z.
const t = new Date(Date.UTC(2024, 6, 9, 12, 30, 5, 120));
console.log(t.toISOString());
console.log(JSON.stringify({ t }));
console.log(new Date(Date.UTC(-1, 0, 1)).toISOString()); // a year before 0 has six digits and a sign

// With no offset, a date-only text is UTC, but a date-time text is local time.
console.log(new Date("2024-07-09").toISOString());
console.log(new Date("2024-07-09T00:00").toISOString());
console.log(new Date("2024-07-09T00:00Z").toISOString());

// Week dates and ordinal dates are not in the format of Date.
console.log(Number.isNaN(Date.parse("2024-W28-2")), Number.isNaN(Date.parse("2024-191")));
Output
2024-07-09T12:30:05.120Z
{"t":"2024-07-09T12:30:05.120Z"}
-000001-01-01T00:00:00.000Z
2024-07-09T00:00:00.000Z
2024-07-09T04:00:00.000Z
2024-07-09T00:00:00.000Z
true true
  • Verdict: native. Date has its own format, a simplified form of ISO 8601. toISOString() and JSON.stringify always write UTC with milliseconds. A text with no offset is UTC if it has only a date and local time if it has a time, so the same day gives two instants here. Temporal adds ISO 8601 durations and the zone suffix of RFC 9557.
package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Date(2024, 7, 9, 14, 30, 5, 120_000_000, time.FixedZone("", 2*60*60))
	fmt.Println(t.Format(time.RFC3339))
	fmt.Println(t.Format(time.RFC3339Nano)) // trailing zeros of the fraction are dropped
	fmt.Println(t.UTC().Format(time.RFC3339Nano))
	fmt.Println(t.Format(time.DateOnly))

	// ISOWeek gives the week-numbering year and the week. Go counts Sunday as 0, ISO 8601 counts it as 7.
	d := time.Date(2024, 12, 30, 0, 0, 0, 0, time.UTC)
	year, week := d.ISOWeek()
	fmt.Printf("%d-W%02d-%d\n", year, week, (int(d.Weekday())+6)%7+1)

	// time.RFC3339 as a layout for Parse accepts a fraction, but it needs the T and an offset.
	for _, s := range []string{"2024-07-09T12:30:05Z", "2024-07-09T18:00:05.12+05:30", "2024-07-09 12:30:05Z", "2024-07-09T12:30:05"} {
		u, err := time.Parse(time.RFC3339, s)
		if err != nil {
			fmt.Println(s, "error")
			continue
		}
		fmt.Println(s, u.UTC().Format(time.RFC3339Nano))
	}
}
Output
2024-07-09T14:30:05+02:00
2024-07-09T14:30:05.12+02:00
2024-07-09T12:30:05.12Z
2024-07-09
2025-W01-1
2024-07-09T12:30:05Z 2024-07-09T12:30:05Z
2024-07-09T18:00:05.12+05:30 2024-07-09T12:30:05.12Z
2024-07-09 12:30:05Z error
2024-07-09T12:30:05 error
  • Verdict: stdlib. The package time has the layouts time.RFC3339 and time.RFC3339Nano for the profile of RFC 3339, and ISOWeek for week numbers. It has no parser for week dates, ordinal dates or durations, and time.ParseDuration uses its own form such as 1h30m, not PT1H30M.
BashGitHub
export TZ=UTC
# printf has the strftime conversions: %F is %Y-%m-%d and %T is %H:%M:%S.
printf '%(%FT%TZ)T\n' 1735560000
printf '%(%G-W%V-%u %Y-%j)T\n' 1735560000

# GNU date reads ISO 8601 text with an offset and writes the extended format with -I.
date -u -d '2024-07-09T14:30:05+02:00' -Iseconds
date -u -d '2024-07-09T14:30:05.12+02:00' -Ins
TZ=Asia/Kolkata date -d @1720528205 -Iseconds
Output
2024-12-30T12:00:00Z
2025-W01-1 2024-365
2024-07-09T12:30:05+00:00
2024-07-09T12:30:05,120000000+00:00
2024-07-09T18:00:05+05:30
  • Verdict: idiom. Bash has no date type. printf '%(...)T' formats a count of seconds with the conversions of strftime, and GNU date parses ISO 8601 text and writes it with the option -I. Note the comma in the fraction of -Ins: ISO 8601 allows a comma or a full stop there, but RFC 3339 allows only the full stop.

Versions

The first edition, ISO 8601:1988, was published in June 19881. It replaced older ISO standards, such as ISO 2014 for all-numeric dates and ISO 2015 for the numbering of weeks. New editions followed in 2000 and 2004. In February 2019 the standard became two parts. ISO 8601-1:2019 has the basic rules. ISO 8601-2:2019 "is entirely new. It defines various extensions such as uncertainties or parts of the Extended Date/Time Format (EDTF)."1 An amendment to part 1 in 2022 brought back 24:00:00 for the end of a day1.

The text of the standard is sold by ISO, so most programmers read RFC 3339 and the documentation of their libraries instead. RFC 3339 was published in July 2002, and RFC 9557 updated it in April 20243.

Pitfalls

  • JavaScript reads a missing offset in two ways. "When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time."4 In New York, new Date('2024-07-09') is midnight UTC, but new Date('2024-07-09T00:00') is midnight local time, 4 hours later. MDN calls the first rule "a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility"4. Always write the offset.
  • The week-numbering year in patterns. In Java, the pattern letter Y is the "week-based-year"5, so the pattern YYYY-MM-dd writes 2024-12-30 as 2025-12-30. Use uuuu or yyyy. In strftime, %G is the week-based year and %Y is the year6.
  • A local time is not an instant. 2024-07-09T14:30:05 with no offset is valid ISO 8601, but it does not name one moment. RFC 3339 requires the offset. Store Z or an offset with each timestamp.
  • An offset is not a zone. +02:00 does not say that the time is in Paris. A program that adds six months to it gets the wrong local time in winter. Use the zone suffix of RFC 9557 or store the zone name. See Time zone.
  • Parsers accept different subsets. No common library accepts all of ISO 8601. Python's date.fromisoformat rejects reduced precision: "Reduced precision dates are not currently supported (YYYY-MM, YYYY)."7 Go's time.RFC3339 layout needs the T and the offset. Agree on a profile, usually RFC 3339, and test the parser with each form you accept.
  • Fractions of seconds. Libraries write different numbers of digits. toISOString() always writes milliseconds and is "always 24 or 27 characters long"8. The .NET format "o" writes 7 digits, and Python writes 6 digits or none. Compare instants, not strings.
  • Z and +00:00. Python writes +00:00 for UTC, and JavaScript writes Z. Both are the same instant, but a check that compares text or expects one of them fails. Since RFC 9557, the two also differ in meaning: Z says that the local offset is unknown.
  • Basic offsets from %z. strftime writes +0530, the basic format, even when the rest of the text uses the extended format. C++ has %Ez for +05:30.
  • Sorting text. Text sorts in time order only when all values use the same form, the same offset and the same number of fraction digits. Convert to UTC and use one form before you sort strings.

Tools and libraries

  • Python: datetime.isoformat() and fromisoformat(). fromisoformat() reads most forms of ISO 8601; older versions read only the output of isoformat()7.
  • JavaScript: Date.prototype.toISOString() and the format of Date.parse, "a simplified format based on ISO 8601"8. Temporal reads and writes RFC 9557 and durations.
  • Java: DateTimeFormatter has predefined formatters such as ISO_LOCAL_DATE, ISO_OFFSET_DATE_TIME, ISO_WEEK_DATE, ISO_ORDINAL_DATE and BASIC_ISO_DATE5. Duration and Period read durations.
  • .NET: the format specifier "o", the "round-trip date/time pattern"9, System.Globalization.ISOWeek, and XmlConvert for durations.
  • Go: the layouts time.RFC3339 and time.RFC3339Nano, whose layout text is 2006-01-02T15:04:05Z07:0010.
  • C and C++: the strftime conversions %F, %T, %G, %V, %u, %j and %z, and in C++ std::format and std::chrono::parse.
  • HTML: the datetime attribute of the time element holds a date, a time or a duration in a form close to ISO 8601.

References

  1. ISO 8601, Wikipedia, Introduction; History; General principles; Week dates; Durations; Time intervals
  2. G. Klyne, C. Newman, RFC 3339: Date and Time on the Internet: Timestamps, July 2002, Abstract; 4.3 Unknown Local Offset Convention; 5.6 Internet Date/Time Format
  3. U. Sharma, C. Bormann, RFC 9557: Date and Time on the Internet: Timestamps with Additional Information, April 2024, Abstract; 1 Introduction; 4 Syntax Extensions to RFC 3339
  4. Date, MDN Web Docs, Date time string format
  5. Class DateTimeFormatter, Java SE 25 API, Predefined Formatters; Patterns for Formatting and Parsing
  6. strftime, The Open Group Base Specifications Issue 8 (POSIX.1-2024), Description
  7. datetime, Basic date and time types, The Python Standard Library, date.fromisoformat; datetime.fromisoformat
  8. Date.prototype.toISOString(), MDN Web Docs, Description
  9. Standard date and time format strings, .NET, The round-trip ("O", "o") format specifier
  10. Package time, Go standard library, Constants

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source