对 NSDateComponents 的困惑

Confusion over NSDateComponents

如果新的一天开始,我有这个方法删除字典中的所有对象:

-(void)flushDictionaryIfNeeded{

    NSLog(@"Flush called");
    if([self.messagedTodayDict count]>0) {

        //get any date
        NSDate *aDate = nil;
        NSArray *values = [self.messagedTodayDict allValues];
        aDate = [values objectAtIndex:0];

        NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:aDate];
        NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
        NSLog(@"Today is %@",[NSDate date]);
        NSLog(@"Date in the dicitonary is %@",aDate);

        if([today day] == [otherDay day] &&
           [today month] == [otherDay month] &&
           [today year] == [otherDay year] &&
           [today era] == [otherDay era]) {

            NSLog(@"Don't flush");
        }

        else {

            NSLog(@"It's a new day! erase dictionary!");
            [self.messagedTodayDict removeAllObjects];

        }

    }

}

我住在台湾,我打印的任何日期的 NSLog 都比这里晚 8 小时。我在午夜前五分钟(台湾时间)调用这个方法,我得到这个:

Today is 2015-04-03 15:55:09 +0000
Date in the dicitonary is 2015-04-03 15:09:09 +0000

这是有道理的,日期存储为 8 小时后并且字典没有 flush/delete 所有对象。

现在半夜调用方法:

Today is 2015-04-03 16:00:22 +0000
Date in the dicitonary is 2015-04-03 15:09:09 +0000

并且字典删除了所有对象。如果我比较下面的日期组件,为什么会这样做?今天的月份和日期与字典中的日期相同。不太明白这里发生了什么。非常感谢一些指点。

当您直接 NSLog 日期对象时,您会像上面那样获得 UTC 日期。但日期组件将根据您当地的时区(除非您修改时区)。 [NSCalendar currentCalendar] 根据您当前的区域设置为您提供日历,包括时区 (see here)。

如果您想正确记录日期,请使用 NSDateFormatter:

NSDateFormatter* formatter = [NSDateFormatter new];
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterLongStyle;
NSLog(@"%@",[fomatter stringFromDate: yourDate]);

可以使用您想要的任何 time/date 样式(短、中、长、全),也可以使用 date formatting syntax

设置自定义格式