计算2个时间间隔之间的时间差 - 逻辑问题

时间:2012-05-30 00:49:12

标签: iphone objective-c ios nsdate nstimeinterval

我有一个字符串,时间如下;

NSString *time = "06.45 pm";

我需要假设这个时间是今天的日期,然后得到当前系统时间,并计算两者之间的时差。

我该怎么做?

注意:上述时间未指定date,(仅给出时间)

2 个答案:

答案 0 :(得分:3)

NSString *time = @"06.45 pm";

NSDate *date1;
NSDate *date2;
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh.mm a"];
    date1 = [formatter dateFromString:time];
    date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
    [formatter release];
}
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;

NSLog(@"%@ %dh %dm", interval<0?@"-":@"+", ABS(hour), ABS(minute));

答案 1 :(得分:2)

确保在执行此操作时使用日历操作,以便考虑时间更改(夏令时,闰秒等):

NSString    *time  = @"06.45 pm";
NSCalendar  *cal   = [NSCalendar currentCalendar];
NSDate      *today = [NSDate date];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh.mm a"];

// Convert time to a NSDate and break it down into hours, minutes, and seconds:
NSDate           *timeAsDate = [formatter dateFromString:time];
NSDateComponents *timeComps  = [cal components:NSHourCalendarUnit |
                                               NSMinuteCalendarUnit |
                                               NSSecondCalendarUnit
                                      fromDate:timeAsDate];

// Take today's date and add "time" to it:
NSDateComponents *comps  = [cal components:NSYearCalendarUnit |
                                           NSMonthCalendarUnit |
                                           NSDayCalendarUnit
                                  fromDate:today];
comps.hour               = timeComps.hour;
comps.minute             = timeComps.minute;
comps.second             = timeComps.second;
NSDate *timeOnTodaysDate = [cal dateFromComponents:comps];

// Now calculate the difference:
NSTimeInterval difference = [today timeIntervalSinceDate:timeOnTodaysDate];