-1

I have this method that deletes all the objects in the dictionary if a new day has begun:

-(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];

        }

    }

}

I live in Taiwan, the NSLog for any date I print is 8 hours behind the time here. I call this method five minutes before midnight (Taiwan time) I get this:

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

This makes sense, dates stored as 8 hours behind and the dictionary doesn't flush/delete all objects.

Now I call the method at midnight:

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

and the dictionary deletes all the objects. Why does it do this if I am comparing date components below? The month and day are the same for today and the date in the dictionary. Don't really understand what is happening here. Some pointers would be really appreciated.

Kex
  • 8,023
  • 9
  • 56
  • 129

1 Answers1

2

When you NSLog a date object directly you get the date in UTC like you have above. But the date components will be according to your local time zone (unless you modify the time zone). [NSCalendar currentCalendar] gives you the calendar based on your current locale, including time zone (see here).

If you want to log dates properly, use an NSDateFormatter:

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

Can use whatever time/date style you want (short, medium, long, full) or can also set a custom format using date formatting syntax

shim
  • 9,289
  • 12
  • 69
  • 108
  • Thanks a lot for this. This method is occasionally deleting all elements in the dictionary when it shouldn't (when it hasn't yet past midnight) so trying to understand how the dates are stored and displayed. Thanks – Kex Apr 03 '15 at 16:24