Use the NSCalendar class to compare dates.
In the project, the date display usually displays the time of the current day, the display date and minute of the current month, and so on. It is inevitable that the date comparison will be involved. The following describes two methods for date comparison.
There are two methods to compare dates
One is implemented through the NSCalendar class of the system.
NSString * date = @ "13:12:12 ";
// Creation date format
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[DateFormat setDateFormat: @ "yyyy-MM-dd HH: mm: ss"];
[DateFormat setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @ "en_US"];
// Convert string to date
NSDate * showDate = [dateFormat dateFromString: date];
// Create a calendar class
NSCalendar * calendar = [NSCalendar currentCalendar];
// Compare the current time and
NSDateComponents * components = [calendar components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate: showDate toDate: [NSDate date] options: NSCalendarWrapComponents];
If (components. year ){
NSLog (@ "Same year ");
} Else {
If (components. month ){
NSLog (@ "Same as January ");
} Else {
NSLog (@ "different months ");
}
}
Another method is:
Using the time instance method timeIntervalSinceDate: two seconds of time difference are obtained, and the number of days of the difference is calculated.
NSString * date = @ "9:04:00"; // create date Format NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat: @ "yyyy-MM-dd HH: mm: ss "]; [dateFormat setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @" en_US "]; // convert string to date NSDate * showDate = [dateFormat dateFromString: date]; NSDate * nowDate = [NSDate date]; NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate: showDate]; NSLog (@ "Difference = % f", timeInterval/60.00 ); // differential NSLog (@ "Time Difference = % f", timeInterval/3600.00); // time difference NSLog (@ "days difference = % f", timeInterval/3600.00/24 ); // The number of days is poor. If it is 0, it indicates the day, otherwise it is not the day.