Getting precise timestamps and differences in time
What is the best way to get timestamps in iOS and then calculate time on e.g. 2 timestamps?
What data type is it? and if it is NSTimeInterval, can this value be 开发者_C百科stored in a dictionary that is then written to a plist?
Unix time is best. Indeed, using NSTimeInterval makes it really easy to calculate dates. It's just a double, so:
NSDate *startDate;
NSDate *endDate;
NSTimeInterval interval;
// assuming start and end dates have a value
interval = [endDate timeIntervalSince1970] - [startDate timeIntervalSince1970];
When the dictionary is to be serialised or written to a document database like Couch or Mongo, I usually record the time interval as a NSString:
NSDate *dateToStore;
// assume dateToStore has a value
NSTimeInterval aTimeInterval = [dateToStore timeIntervalSince1970];
NSString *aStringObject = [NSString stringwithFormat:@"%f", aTimeInterval];
NSDictionary *aDict = [NSDictionary dictionaryWithObject:dateAsString
forKey:@"aKey"];
Then you can just read it back again when you use the dictionary object:
NSTimeInterval newTimeInterval = [[aDict valueForKey:"aKey"] doubleValue];
NSDate *retreivedDate = [NSDate dateWithTimeIntervalSince1970:newTimeInterval];
If it's going to plist, you can just skip the string conversion.
NSTimeInterval is a typedef of double. So you can add a time interval value to a dictionary as NSNumber by using,
NSNumber *ti_num = [NSNumber numberWithDouble:aTimeInterval];
Just take a look at NSDate
reference. All you need is there.
精彩评论