我已经尝试过NSDate,但没有运气。 我想要例如14:10和18:30之间的区别。
小时和分钟。
我希望你能帮助我不要那么复杂:)
答案 0 :(得分:30)
无需手动计算,请查看NSCalendar
。如果您想获得两个日期之间的小时和分钟,请使用以下内容:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:firstDate
toDate:otherDate
options:0];
[gregorianCalendar release];
您现在拥有NSDateComponents的小时和分钟,可以NSIntegers
和[components hour]
[components minute]
访问它们。这也可以在几天,闰年和其他有趣的东西之间工作几个小时。
答案 1 :(得分:18)
这是我的快速解决方案:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"HH:mm"];
NSDate *date1 = [df dateFromString:@"14:10"];
NSDate *date2 = [df dateFromString:@"18:09"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:@"%d:%02d", hours, minutes];
答案 2 :(得分:12)
NSDate类有一个方法timeIntervalSinceDate来完成这个技巧。
NSTimeInterval secondsBetween = [firstDate timeIntervalSinceDate:secondDate];
NSTimeInterval是一个双精度数,表示两次之间的秒数。
答案 3 :(得分:7)
NSString *duration = [self calculateDuration:oldTime secondDate:currentTime];
- (NSString *)calculateDuration:(NSDate *)oldTime secondDate:(NSDate *)currentTime
{
NSDate *date1 = oldTime;
NSDate *date2 = currentTime;
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int hh = secondsBetween / (60*60);
double rem = fmod(secondsBetween, (60*60));
int mm = rem / 60;
rem = fmod(rem, 60);
int ss = rem;
NSString *str = [NSString stringWithFormat:@"%02d:%02d:%02d",hh,mm,ss];
return str;
}