2015-04-03 116 views
-1

我有这样的方法删除字典中的所有对象,如果新的一天又开始了:混淆了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小时这里。我把这种方法5分钟午夜前(台湾时间)我得到这样的:存储8小时的背后

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

这是有道理的,日期和字典不冲水/删除所有对象。

现在我调用该方法在午夜:

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

和字典中删除的所有对象。为什么如果我在比较下面的日期组件呢?今天的日期和日期与字典中的日期相同。真的不明白这里发生了什么。一些指针将非常感激。

回答

2

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

如果要正确登录日期,使用NSDateFormatter:

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

可以使用任何你想要的时间/日期样式(短,中,长,满),或者也可以设置使用date formatting syntax自定义格式

+0

非常感谢。此方法偶尔会删除字典中的所有元素(当它尚未过午夜时),以便了解日期如何存储和显示。谢谢 – Kex 2015-04-03 16:24:07