如何计算旅行时间的总和

时间:2014-05-23 19:12:19

标签: ios objective-c nsstring nsdate

我需要NSString使用2 NSStrings

显示总行进时间

我有

NSString *origin = [NSString stringWithFormat:@"5:30"];
NSString *destiny = [NSString stringWithFormat:@"6:00"];

问题是,我不知道如何将此NSStrings格式化为NSDate并执行destiny - origin,因此输出将是NSString,表示{ {1}}

编辑:我只是对30 minutes进行了一些调查,但是如果我使用它的话:

NSDateFormatter

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH:mm"]; NSDate * mydate = [dateFormatter dateFromString:origin]; 给我一个NSDate有什么不对吗?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

NSString *origin = @"5:30";
NSString *destiny = @"6:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];

NSTimeInterval diffInSeconds = [destinyDate timeIntervalSinceDate:originDate];
NSTimeInterval diffInMinutes = diffInSeconds / 60;
NSString *minutesString = [NSString stringWithFormat:@"%0.0f", diffInMinutes];

答案 1 :(得分:0)

NSString *origin = @"5:30";
NSString *destiny = @"6:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"H:mm"];

NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];

NSTimeInterval interval = [destinyDate timeIntervalSinceDate:originDate];
NSDate *intervalDate = [NSDate dateWithTimeInterval:interval sinceDate:originDate ];

NSDateComponents *comps =[[NSCalendar currentCalendar] components:NSMinuteCalendarUnit
                                                         fromDate:originDate
                                                           toDate:intervalDate
                                                          options:0];

现在NSDateComponents将在几分钟内保持差异

NSLog(@"%ld", [comps minute]);

将记录30

如果您想要小时和分钟,可以

NSString *origin = @"5:30";
NSString *destiny = @"7:00";

// .... 

NSDateComponents *comps =[[NSCalendar currentCalendar] components: (NSMinuteCalendarUnit|NSHourCalendarUnit)
                                                         fromDate:originDate
                                                           toDate:intervalDate
                                                          options:0];

现在比赛将持续90分钟为1小时30分钟。

NSLog(@"%ld %ld", [comps hour],[comps minute]);

记录1 30