问题
Here is the code:
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
currentTime = [currentTime stringByReplacingOccurrencesOfString:@"AM" withString:@""];
currentTime = [currentTime stringByReplacingOccurrencesOfString:@"PM" withString:@""];
currentTime = [currentTime stringByReplacingOccurrencesOfString:@" " withString:@""];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date1= [formatter dateFromString:currentTime];
NSDate *date2 = [formatter dateFromString:@"5:00:00"];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(@"date1 is later than date2");
}
Here when I run the code I am getting date1 and date2 as nil, while I am properly getting the current time in 24 hour format. I had applied same date formatting while getting current time from [NSDate date] . What am I missing here?
EDIT 1: Fixed the typo and changed the title.
EDIT 2: As per suggestion, To compare Only the hour I can use:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit) fromDate:date1];
NSInteger hour = [components hour];
EDIT 3: Changed the title, to match the exact requirements.
But I am not able to retrieve date1 from current time. It throws a garbage value .
回答1:
There was a typo:[dateFormatter setDateFormat:@"HH:mm:ss"];
should be:[formatter setDateFormat:@"HH:mm:ss"];
To compare two dates use:
NSDate *date1 = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date2 = [formatter dateFromString:@"05:00:00"];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(@"date1 is later than date2");
}
If you only want to compare the hours:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date1 = [NSDate date];
NSDateComponents *date1Components = [calendar components:NSCalendarUnitHour fromDate:date1];
NSInteger date1Hour = date1Components.hour;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date2 = [formatter dateFromString:@"05:00:00"];
NSDateComponents *date2Components = [calendar components:NSCalendarUnitHour fromDate:date2];
NSInteger date2Hour = date2Components.hour;
if(date1Hour > date2Hour) {
NSLog(@"date1 is later than date2");
}
来源:https://stackoverflow.com/questions/25571399/how-to-compare-two-time-from-nsdate-returning-nil-for-nsdate-when-doing-compari