Search code examples
swiftdateiso8601

Is it possible to specify an ISO Date with a timezone (i.e. GMT offset) but without a time?


I'm trying to see if you can specify a date with a timezone in ISO but without also specifying a time.

This may seem odd to ask about having a timezone without actually having a time, but technically a date represents a range between two times... the 24-hour period spanning from midnight to midnight, and that 'midnight' has to be in a timezone.

In our case, we have an API that wants to say 'Filter things on-or-before date X and on-or-after date Y' and we want the user to specify 'April 9th' (in their time zone) for both to get all things that happen on that day.

Of course we solve this by adding a day to the first date, then changing it to a pure 'before', but the front-end is required to do that math. We can't do it on the backend because having to send a date with a time means we would be sending April 9th at midnight, then on the backend adding a day to that, but what if someone passed in 4pm?

We could fail the date if it has a non-midnight time, but then we're back to why pass it in the first place.

So again, can you have a date with a timezone but not have a time component?


Solution

  • To decode ISO8601 dates only with year-month-day and time zone set the appropriate formatOptions of the ISO8601DateFormatter

    let isoFormatter = ISO8601DateFormatter()
    isoFormatter.formatOptions = [.withFullDate, .withTimeZone]