如何计算两个NSDate变量之间的差异?

时间:2015-05-19 13:46:34

标签: objective-c nsdate nsdateformatter

我正在构建一个IOS应用程序,我正在执行以下步骤。

  1. 解析数据。
  2. 获取OpenTime和CloseTime。
  3. 将NSString变量名中的OpenTime和CloseTime设置为openTime和closeTime。
  4. 现在问题是我想计算这两次的不同。

    我得到的价值就像, OpenTime = "00:15:00"CloseTime = "1:30:00"

    Time formate是 - 24小时。

    有人帮助我解决这个问题我是IOS的新手。

5 个答案:

答案 0 :(得分:1)

假设您有两个NSDate变量openTimecloseTime

int calendarUnit = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnit fromDate: openTime   toDate: closeTime  options:0];

int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];

答案 1 :(得分:0)

您可以使用NSDateComponents

NSDate *date = [self getTimeInDateFormatFromString://your time string]; // your method return nsdate from string using nsformatter
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];

你可以使用comp.hour和minute来获得时差。

答案 2 :(得分:0)

NSString *openTime = @"12:48:00";
NSString *closingTime = @"21:52:00";

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"hh:mm:ss"];

NSDate *openDate = [formatter dateFromString:openTime];
NSDate *closeDate = [formatter dateFromString:closingTime];

int calendarUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnits fromDate: openDate toDate: closeDate options:0];

NSLog(@"The difference is: %ld hours , %ld minutes, %ld seconds", (long)components.hour, (long)components.minute, (long)components.second);

答案 3 :(得分:0)

-(void)compareTwoDate:(NSDate *)start :(NSDate *)end
{
    NSDate *end_date =end;
    NSDate *startDate =start;

    NSTimeInterval distanceBetweenDates = [startDate    timeIntervalSinceDate:end_date];

    double secondsInMinute = 60;

    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
}

答案 4 :(得分:0)

NSArray *star_array=[@"00:15:00" componentsSeparatedByString:@":"];

NSInteger start_time=[[star_array objectAtIndex:2] integerValue]*3600+[[star_array objectAtIndex:1] integerValue]*60+[[star_array objectAtIndex:0] integerValue];

NSArray *end_array=[@"1:30:00" componentsSeparatedByString:@":"];
NSInteger end_time=[[end_array objectAtIndex:2] integerValue]*3600+[[end_array objectAtIndex:1] integerValue]*60+[[end_array objectAtIndex:0] integerValue];

NSInteger diff_seconds=end_time-start_time;