Compare two time values in ios?
ios, nsdate, nsstring, time
Solution
Use the following code to do the convert from the nsstring to nsdate and compare them.
NSString *time1 = @"08:15:12";
NSString *time2 = @"18:12:08";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(@"date1 is later than date2");
}
else if(result == NSOrderedAscending)
{
NSLog(@"date2 is later than date1");
}
else
{
NSLog(@"date1 is equal to date2");
}
Problem
In my app i want to check whether the current time is before or after the time saved in a variable. like my time1 is `time1=@"08:15:12";` and my time2 is `time2=@"18:12:8";` so i wanna compare between time1 and time2.Currently these variables are in NSString Format. Following are the code used to get time,and i dont know how to compare them. CODE: ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"HH:MM:SS"; [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; NSLog(@"ewetwet%@",[dateFormatter stringFromDate:now]); ``` Please help me