How to store dates without times in Core Data

前端 未结 3 1477
傲寒
傲寒 2020-12-15 10:05

I\'ve been trying to find a sensible way of storing daily data using Core Data on the iPhone.

My app receives data in csv format, with a date but no time:

         


        
3条回答
  •  感情败类
    2020-12-15 11:10

    A good programming rule of thumb is to always store dates in UTC. It doesn't matter whether you use Core Data or not; you'll still have to do some work because Apple's date classes pretty much suck.

    Dates are represented internally as a number of seconds since a reference date which is, I believe, 1 January 2001 00:00:00 (although the actual reference date isn't very important). Point is, NSDate objects are always natively in UTC. If the dates you're getting in your CSV file are local, you'll need to do something like this to get the UTC time:

    NSDate *UTCDate = [localDate addTimeInterval:-[[NSTimeZone localTimeZone] secondsFromGMT]];
    

    Then, I'd set the time to 00:00:00. Now you're saving the date, at midnight, in UTC. For presentation purposes, you will use an NSDateFormatter configured with the time zone of your choice (the system time zone is the default if you don't specify one) to display those dates.

    Time zones don't really matter when you're just dealing with dates, though. As long as you make sure to set the time zone on your NSDateFormatter to UTC, you'll always show the same date, no matter what time zone the user has selected on her device.

    If you don't like this solution, you can always store your dates in an alternative format. You could use a double or int to store the date in some custom format (e.g. the number of days since some reference date), or you could even roll your own class to model the date exactly the way you want and store it as an NSData object. As long as the class implements NSCoding, you can serialize it to an NSData object in Core Data. You just need to set the attribute type in Core Data to "Transformable".

    You have a ton of options here, and none of them involve the effort of writing your own SQLite queries and databases.

提交回复
热议问题