Search code examples
datetimeiso8601isodate

ISO 8601 Date Portion ONLY


Our front end wants only a date. My understanding is that the industry standard for JSON.NET and Web Api is ISO 8601. Is is possible to return a date portion ONLY from our Web Api while adhering to ISO 8601 standards, or will the date property (dateOfBirth) of our JSON object have to have all zeroes for the time portion in order to adhere to the ISO 8601 standard?


Solution

  • ISO 8601 is a standard that specifies many different formats. Section 4.1.2 covers dates, section 4.2.2 covers time of day, and section 4.3 covers date and time of day combined. The spec also defined a "basic format" and an "extended format" for each.

    Some examples in the basic format:

    • Date: 20190611
    • Local time: 140000
    • Date and local time: 20190611T140000

    Some examples in the extended format:

    • Date: 2019-06-11
    • Local time: 14:00:00
    • Date and local time: 2019-06-11T14:00:00

    Also there are variations to the time of day which add Z for UTC or a specific offset from UTC such as -07:00. (These do not apply to the date-only form.)

    Thus, to answer your question directly, yes you can pass just the date. That is still ISO 8601 compliant, as long as you use either of the date-only forms shown above. (The extended form is usually chosen for JSON responses.)

    By the way, this isn't just an option, it's a best practice. Date-only value such as birth dates and other anniversary dates should not have a time attached - even if it's all zeros. Doing so contorts their meaning.

    That said, be aware of some pitfalls:

    • Some platforms do not have a built-in date-only data type, and will assign midnight.
    • JavaScript's Date object (via the ECMAScript standard) deviates from ISO 8601 and parses date-only values as if they were at midnight UTC instead of midnight local time. Thus if you are calling your API from a web page, you may want to parse the values yourself, or use a library, or leave them as strings instead of Date objects.
    • There are certain time zones that have days with forward transitions (such as for DST) right at midnight, meaning the clocks tick from 23:59:59 to 01:00:00. If you specify midnight, some implementations will go forward, some will go backward, and some will error.

    If you have to parse a date-only value to a date-time data type, one way to avoid these problems is to assign noon (12:00) instead of midnight (00:00).

    Also, you may want to make sure ISO 8601 is indeed the standard you need to comply with. Many people say ISO 8601 when they actually mean RFC 3339. RFC 3339 is mostly compliant with ISO 8601, but only defines a date + time + offset profile. Thus it is appropriate for timestamps, but not whole dates.