I’ve seen a few questions which float around this topic but nothing which quite matches.
I’m creating a Timestamp as part of a primary key. The timestamp is set with [NSDate date] and is stored in a SQLite store. When I look into the store the dates have full precision (up to 7 decimal places indicating 100 nanosecond precision).
I have services running on a server which I need to send the data to and retrieve the date from. The sending process serializes the data and in order to send the date with the required precision (stored as datetime2 in SQL Server) I use:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"];
NSString *stringFromDate = [dateFormat stringFromDate:dateTime];
and vice versa when retrieving the date from the server.
The problem is that the date being retrieved from the store is for some reason ONLY at millisecond precision. So if I have a Timestamp in the store as 341196557.808558, retrieve into an NSDate and then use the above code to generate a string is reads as “2011-10-24’T’08:48:17.8090000”.
This gets sent to the server which dutifully stores it as millisecond precision (because that’s all it’s getting). When I then retrieve the date, deserialize it and try and use a predicate fetch against the store it doesn’t return the record because the dates aren’t equal. Doing a < or > comparison won’t work because it’s a primary key… I need ==
I wouldn’t mind dropping to millisecond precision on the timestamp prior to saving (if I could work out how) but it seems extremely odd to me that the original date can store and save microsecond precision but doesn’t keep the same precision when retrieving the date from the store?
Would love any thoughts on this, or that gem one-liner which sorts this mess out…
While I do not know why the nanosecond precision is being dropped (that surprises me and you should file a radar on it) what I can say is that:
Timestamps are a terrible primary key. If you can change that I would highly recommend it.
If you must use Timestamps then I suggest storing the
-timeIntervalSinceReferenceDatein Core Data instead and then reconstruct the date whenever you need to send it to the server.Update
Timestamps are a pain (as you are experiencing) and wasteful from a purely DB point of view since you never use all of them in order.
Depending on what you are trying to do a INT64 incremented (not easy with Core Data) works well. If you are using the timestamp for more than just part of the unique key then I would just keep it as a NSTimeInterval (double) as I suggested above. That will keep your precision and avoid messing with strings. Keep in mind that strings can be quite slow.