我想计算iPhone中两个不同日期之间的天数,小时数,分钟数(目标C)。请提供相同的代码示例。
由于 桑迪普
答案 0 :(得分:4)
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];
然后只检查differenceComponents的属性。您可以在随XCode提供的文档中找到所有这些属性
答案 1 :(得分:4)
如果您的日期在NSDate对象中,您可以使用timeIntervalSinceDate方法将差异作为NSTimeInterval查找,这将为您提供以秒为单位的差异。
然后,你可以通过一个简单的算法将秒数转换为天,小时和分钟(这是我的头脑,而不是测试):
minutes = seconds / 60;
seconds %= 60;
hours = minutes / 60;
minutes %= 60;
days = hours / 24;
hours %= 24;
答案 2 :(得分:2)
我写了一个全面的程序来区分C中的两个日期(不知道这就是Objective C的意思)。请在这里找到原创作品。
http://tech.bragboy.com/2010/02/different-between-two-days-implemented.html
答案 3 :(得分:0)
建立Ferruccio的答案,这样的事情会让你发现时差到一个连接的字符串,你可以告诉你从你比较的日期,时间和分钟到目前为止的数字,
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];