1

I calculate number of days between two dates:

NSDateComponents *datesDiff = [calendar components: NSDayCalendarUnit 
                                          fromDate: someDate
                                            toDate: currentDate
                                           options: 0];

But this method has one disadvantage - it doesn't take in account time zone. So, for example, if I'm in +2GMT and local time is 1:00AM, current date is yesterday.

How to compare dates in specified time zone (without 'hacking')?

PS: Preventing answers with calculation of time difference, I need difference of actual days:

  • yesterday 23:00 vs. today 1:00 - 1 day
  • yesterday 1:00 vs. today 23:00 - 1 day
  • today 1:00 vs. today 23:00 - 0 days

  • (all this in current time zone)

brigadir
  • 6,874
  • 6
  • 46
  • 81
  • Why not convert both to epoch and then figure out how many days its been? – Scott Bartell Sep 10 '12 at 08:53
  • My thought was that if you determine the seconds since epoch for each of the dates and then find the difference between the two.. you could find the number of days by dividing by the number of seconds in a day (86,400). But, there is likely a better way to do this - have you read the [documentation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/doc/uid/20000188-SW6)? – Scott Bartell Sep 10 '12 at 09:15
  • I know about comparing seconds. But this approach gives wrong results - take a look at the example in the end of my question. – brigadir Sep 10 '12 at 13:04

2 Answers2

0

Why don't you configure the dateformatter to default all dates to GMT time and then compare.

    NSDate *now = [NSDate date]; 
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; // Sets to GMT time. 

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setCalendar:gregorianCalendar]; 
    [formatter setTimeZone:timeZone]; 
    [formatter setDateFormat:@"yyyyMMddHH"];

    NSString *dateString = [formatter stringFromDate:now]; 
  // do whatever with the dates
    [gregorianCalendar release]; 
    [formatter release];
s1lntz
  • 389
  • 4
  • 7
  • In GMT time zone, for example 21:00 and 23:00 has 0 days difference, but in GMT+2 (where user lives) it will have 1 day. – brigadir Sep 11 '12 at 06:18
0

I don't know if it meets your criteria of not being hacky, but a fairly simple way seems to be defining a GMT adjusted date something like this:

NSDate *newDate = [oldDate dateByAddingTimeInterval:(-[[NSTimeZone localTimeZone] secondsFromGMT])

See this question for more details.

Community
  • 1
  • 1
Scott Lemmon
  • 694
  • 7
  • 16