There are a lot of date and time formats out there, including both legacy formats and current formats used by different types of apps. Over time, many applications have converged on RFC-3339, a more strict interpretation of ISO-8601. This looks like the following:
You can see more on these formats in the RFC: https://tools.ietf.org/html/rfc3339
That being said, there are APIs that don’t follow these formats and people may think “what’s the harm”? Here are real API formats I’ve run across and have worked with:
11/7/2015 8:07:05 AM—
M/d/yyyy h:mm:ss AM/PM
Non-standard APIs actually cause interoperability problems because the OpenAPI 3.0 and Swagger 2.0 API specifications only support RFC-3339 which means the dates cannot be adequately represented in the spec or used by a variety of API ecosystem tools. Some APIs will further publish an incorrect spec use the
date-time formats in the Spec for non-compliant parameters, causing tools to fail.
So we have the following:
- Design Name: Non-Standard Date and Time Formats — string type only
- Interop Score: 2
- Design Name: Non-Standard Date and Time Formats — incorrect spec format
- Interop Score: 1
This article discusses the importance of adhere to this standard and how to handle it if you cannot.
In practice, when
format=date-time auto-generated code may attempt to auto-parse and format time objects. For example, OpenAPI Generator for Go will automatically convert a string to a
type=string with no
format information, the developer will need to manually parse the time.
format is set to
date-time, the auto-generated SDK will actually produce an error when a non-RFC-3339 date is encountered. The following error will be encountered when attempting to parse a JSON response:
parsing time ""11/7/2015 8:07:05 AM"" as ""2006-01-02T15:04:05Z07:00"": cannot parse "/2015 8:07:05 AM"" as "2006"
When I run to spec written this way, I need to pre-process the spec to remove the incorrect
Extending the OpenAPI Specification
One approach for the future, may be to extend the OpenAPI specification but this does not seem likely.
I proposed a more flexible approach for handling times using a
strftime or Go time format string, but it did not receive much support. In fact, one person stated that such APIs should be made difficult to use:
using alternate format for dates is probably a bad practice
that should be blamed and made difficult
we should strive to harmonization and not prolification
While I agree with harmonization, I also prefer working to not working, so the current recommendation is to use RFC-3339 dates and times.
Read more here:
To make your API compatible:
- Use RFC-3339 date and date-time formats. Even if you have different internal formats, such as for interfacing with databases, do a time conversion if your API layer to publish and consume RFC-3339 date and time formats.
- If you cannot use RFC-3339, use
type=stringand do not use