Reputation: 1834
I'm calculating difference between two dates. I've create my own solution:
NSDate *actualDate = [NSDate date];
NSTimeInterval sec = [eveDate timeIntervalSinceDate:actualDate];
int secondsBetween = sec;
int minBetween = sec / 60;
int hoursBetween = sec / 3600;
int daysBetween = sec / 86400;
_lblDays.text = [NSString stringWithFormat:@"%d", daysBetween];
_lblHours.text = [NSString stringWithFormat:@"%d", hoursBetween % 24];
_lblMin.text = [NSString stringWithFormat:@"%d", minBetween % hoursBetween];
_lblSec.text = [NSString stringWithFormat:@"%d", secondsBetween % minBetween];
But I believe that there is a better solution for this (like native class for example) but I couldn't find anything. Could you tell me how to do it better?
Upvotes: 2
Views: 96
Reputation: 107131
You can use NSCalendar and NSDateComponents class for doing this:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:actualDate toDate:eveDate options:0];
NSLog(@"Days->%d Hour->%d, Minute->%d, Second->%d", components.day, components.hour, components.minute, components.second);
Upvotes: 0
Reputation: 801
This is an another way to calculate.
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond
fromDate: startDate toDate: endDate options: 0];
NSInteger days = [components day];
NSInteger hour=[components hour];
NSInteger minutes=[components minute];
NSInteger sec = [components second];
Upvotes: 8