SwiftData
SwiftData copied to clipboard
Dates
I notice that you're writing dates using NSDateFormatter
. I'd really encourage you to specify a timezone for your formatter in case the timezone of the device changes at any point. As you've implemented the date logic, dates are stored in the device's then local time zone which can be problematic.
I'd suggest
- using a date formatter that specifies time zone (e.g. store date strings as Zulu/GMT/UTC,
NSTimeZone(forSecondsFromGMT: 0)
and include the timezone in the date string, e.g.Z
; and - locale (e.g. the one used for RFC 3339/ISO8601 dates is
NSLocale(localeIdentifier: "en_US_POSIX")
; see Q&A 1480).
You might even want to follow one of the established standards, such as ISO8601 format, e.g. 2015-02-03T15:29:00.000Z
, in which the format is sortable and unambiguous.
By the way, while this is a somewhat minor issue (though, IMHO, still important) when dealing with data that the end user writes to the database themselves, it's a huge deal when dealing with a database that the app developer includes in a database that they distribute with the app (in which the timezone and locale is that of the app developer, which is, more than likely, completely different from the users').
I also had difficulty with this...