1

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

NSString *time = "06.45 pm";

我需要假设这个时间是今天的日期,然后获取当前的 System time,并计算两者之间的时间差。

我怎样才能做到这一点 ?

注:以上时间未指定a date,(仅给出时间)

4

2 回答 2

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));
于 2012-05-30T01:13:11.057 回答
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];
于 2012-05-30T01:59:34.630 回答