How to get difference between two days in iPhone
I would like to calculate 开发者_开发技巧the no of days,hours,minutes between two different dates in iPhone(Objective C). Please provide any code sample to do the same.
Thanks Sandeep
If your dates are in NSDate objects, you can use the timeIntervalSinceDate method to find the difference as an NSTimeInterval, which will give you the difference in seconds.
You can then convert seconds to days, hours and minutes via a simple algorithm (this is off the top of my head and not tested):
minutes = seconds / 60;
seconds %= 60;
hours = minutes / 60;
minutes %= 60;
days = hours / 24;
hours %= 24;
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int uintFlags = NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit;
NSDateComponents* differenceComponents = [gregorian components:uintFlags fromDate:firstDate toDate:secondDate options:0];
then just check properties of differenceComponents. You can find all these properties in the documentation provided with XCode
I have written a comprehensive program to give the difference between two dates in C (dont know this is what you mean by Objective C). Please find the original work here.
http://tech.bragboy.com/2010/02/different-between-two-days-implemented.html
Building off Ferruccio's answer, something like this will get you from finding the time difference to a concatenated string where you can tell how many days, hours and minutes from the date you're comparing (YOURNSDATE) till now
NSTimeInterval timeDifference = [[NSDate date] timeIntervalSinceDate:YOURNSDATE];
NSInteger seconds = (NSInteger)timeDifference;
NSInteger minutes;
NSInteger hours;
NSInteger days;
minutes = seconds / 60;
seconds %= 60;
hours = minutes / 60;
minutes %= 60;
days = hours / 24;
hours %= 24;
NSString* daysString = [NSString stringWithFormat:@"%i days ", days];
if(days == 0){
daysString = @"";
}else if(days == 1){
daysString = [NSString stringWithFormat:@"%i day ", days];
}
NSString* hoursString = [NSString stringWithFormat:@"%i hrs ", hours];
if(hours == 0){
hoursString = @"";
}else if(hours == 1){
hoursString = [NSString stringWithFormat:@"%i hr ", hours];
}
NSString* minutesString = [NSString stringWithFormat:@"%i min", minutes];
if(minutes == 0){
minutesString = @"";
}
NSString *AllDatesString = [NSString stringWithFormat:@"%@%@%@", daysString, hoursString, minutesString];
精彩评论