Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 NSDate. Problem is, I don't know what data type to choose for it. Some people advise to store NSTimeInterval, but will it cause miscalculations when user's timezone changes? Maybe it's better to store NSDateComponents (as a "Transformable" data type) or is there another better way to do it?

like image 982
Randex Avatar asked Dec 24 '22 03:12

Randex


1 Answers

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.

like image 197
Martin R Avatar answered Dec 28 '22 10:12

Martin R