How to compare two NSDates: Which is more recent?

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I am trying to achieve a dropBox sync and need to compare the dates of two files. One is on my dropBox account and one is on my iPhone.

I came up with the following, but I get unexpected results. I guess I'm doing something fundamentally wrong when comparing the two dates. I simply used the > < operators, but I guess this is no good as I am comparing two NSDate strings. Here we go:

NSLog(@"dB...lastModified: %@", dbObject.lastModifiedDate);  NSLog(@"iP...lastModified: %@", [self getDateOfLocalFile:@"NoteBook.txt"]);  if ([dbObject lastModifiedDate] < [self getDateOfLocalFile:@"NoteBook.txt"]) {     NSLog(@"...db is more up-to-date. Download in progress...");     [self DBdownload:@"NoteBook.txt"];     NSLog(@"Download complete."); } else {     NSLog(@"...iP is more up-to-date. Upload in progress...");     [self DBupload:@"NoteBook.txt"];     NSLog(@"Upload complete."); }

This gave me the following (random & wrong) output:

2011-05-11 14:20:54.413 NotePage[6918:207] dB...lastModified: 2011-05-11 13:18:25 +0000 2011-05-11 14:20:54.414 NotePage[6918:207] iP...lastModified: 2011-05-11 13:20:48 +0000 2011-05-11 14:20:54.415 NotePage[6918:207] ...db is more up-to-date.

or this one which happens to be correct:

2011-05-11 14:20:25.097 NotePage[6903:207] dB...lastModified: 2011-05-11 13:18:25 +0000 2011-05-11 14:20:25.098 NotePage[6903:207] iP...lastModified: 2011-05-11 13:19:45 +0000 2011-05-11 14:20:25.099 NotePage[6903:207] ...iP is more up-to-date.

回答1:

Let's assume two dates:

NSDate *date1; NSDate *date2;

Then the following comparison will tell which is earlier/later/same:

if ([date1 compare:date2] == NSOrderedDescending) {     NSLog(@"date1 is later than date2"); } else if ([date1 compare:date2] == NSOrderedAscending) {     NSLog(@"date1 is earlier than date2"); } else {     NSLog(@"dates are the same"); }

Please refer to the NSDate class documentation for more details.



回答2:

Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc

eg.

if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {     //do stuff }

timeIntervalSinceReferenceDate converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.



回答3:

NSDate has a compare function.

compare: Returns an NSComparisonResult value that indicates the temporal ordering o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!