objective-c 获取一天中两次之间的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1792512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get time between two times of the day
提问by user134282
I've already tried with NSDate but with no luck. I want the difference between for example 14:10 and 18:30.
我已经尝试过 NSDate 但没有运气。我想要例如 14:10 和 18:30 之间的差异。
Hours and minutes.
小时和分钟。
I Hope you can help me shouldn't be that complicated :)
我希望你能帮助我不应该那么复杂:)
回答by Pascal
There's no need to calculate this by hand, take a look at NSCalendar. If you want to get the hours and minutes between two dates, use something like this:
没有必要手工计算这个,看看NSCalendar。如果您想获取两个日期之间的小时和分钟,请使用以下内容:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:firstDate
toDate:otherDate
options:0];
[gregorianCalendar release];
You now have the hours and minutes as NSDateComponents and can access them as NSIntegerslike [components hour]and [components minute]. This will also work for hours between days, leap years and other fun stuff.
您现在拥有 NSDateComponents 的小时和分钟,并且可以NSIntegers像[components hour]和一样访问它们[components minute]。这也可以在几天、闰年和其他有趣的东西之间工作几个小时。
回答by amrox
Here's my quick solution:
这是我的快速解决方案:
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];
回答by NWCoder
The NSDate class has a method timeIntervalSinceDate that does the trick.
NSDate 类有一个方法 timeIntervalSinceDate 可以解决这个问题。
NSTimeInterval secondsBetween = [firstDate timeIntervalSinceDate:secondDate];
NSTimeInterval is a double that represents the seconds between the two times.
NSTimeInterval 是一个双精度值,表示两次之间的秒数。
回答by MaxEcho
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;
}

