Randex Randex - 3 months ago 10x
iOS Question

What's the correct way to store a time interval in Core Data?

I need to store a time interval in an app's database that will be added occasionally to

. Problem is, I don't know what data type to choose for it. Some people advise to store
, but will it cause miscalculations when user's timezone changes? Maybe it's better to store
(as a "Transformable" data type) or is there another better way to do it?


A minute is 60 seconds, and an hour is 3600 seconds, no matter what the current date, time zone or calendar is. If you want to store the duration "24 hours" then you can store it as a time interval with the value 24*3600.

All larger units, starting with day, must be interpreted according to the current date, time zone and calendar. The duration "one day" can be 23, 24, or 25 hours in regions with daylight savings time. In particular, "24 hours" and "1 day" have a different meaning. The duration "1 month" can be from 28 to 31 days in the Gregorian calendar, and "1 year" can be 365 or 366 days. Other calendars may have other "peculiarities".

Therefore all durations involving "day" or larger units must be stored as date components. Transforming to NSDateComponents is one possibility, alternatively you can add multiple properties "durationDays", "durationMonths", etc to your Core Data entity. This has the advantage that the values can be referred to in fetch requests or sort descriptors.