Comparing date sizes is a common problem in any programming language, and in iOS programming, you typically use NSDate objects to store a time (including dates and times, time zones), and the NSDate class provides a compare method for time comparisons. But sometimes you don't want to know the size of two dates so precisely (by default it compares to seconds), you can use the following implementation:
+ (int) Compareoneday: (NSDate *) oneday withanotherday: (nsdate *) anotherday{ NSDateFormatter *dateformatter = [[ NSDateFormatter alloc] init]; [Dateformatter setdateformat:@ "dd-mm-yyyy"]; NSString *onedaystr = [Dateformatter stringfromdate:oneday]; NSString *anotherdaystr = [Dateformatter stringfromdate:anotherday]; NSDate *datea = [Dateformatter datefromstring:onedaystr]; NSDate *dateb = [Dateformatter datefromstring:anotherdaystr]; Nscomparisonresult result = [Datea compare:dateb]; NSLog (@ "date1:%@, Date2:%@", Oneday, anotherday); if (result = = nsordereddescending) { //nslog (@ "Date1 is in the Future"); return 1; } else if (result = = nsorderedascending) { //nslog (@ "Date1 is in the past"); return-1; } NSLog (@ "Both dates is the same"); return 0; }
Compare the size of two dates in iOS programming