1

试图将这两个日期与 NSDateComponents 结合起来

“2012-09-03 00:00:00 +0000”和“1970-01-01 08:00:00 +0000”

使用以下代码,我得到--> 2012-09-02 11:00:00 +0000

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:session.date];
    NSDate *day3 = [[NSCalendar currentCalendar] dateFromComponents:comps];

    unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:session.start];
    comps.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    day3 = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:day3 options:0];
4

1 回答 1

5

找到了解决方案。

这是答案:

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    cal.timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; <--this is key

    NSDateComponents *comps = [cal components:unitFlags fromDate:session.date];
    comps.hour = 0;
    comps.minute = 0;
    NSDate *day3 = [cal dateFromComponents:comps];

    unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *hourComps = [cal components:unitFlags fromDate:session.start];

    day3 = [cal dateByAddingComponents:hourComps toDate:day3 options:0];

给定上述日期的结果应该是 2012-09-02 08:00:00 +0000

于 2012-08-10T04:29:49.820 回答