-1

I'm trying to use dateByAddingTimeInterval: to add 8 days to my current date but it gives me a weird result.

This is the code I'm using:

-(void)requestForGetEPGChannelsProgramsSucceed:(id)jsonResponse andEpgId:(NSString *)epgId forDate:(NSDate *)forDate dayOffset:(NSInteger)dayOffset

    NSDate *dateWithOffset = [forDate dateByAddingTimeInterval:(dayOffset * 86400.0)];

forDate represents the date of today with hour 0 and minutes 0. For this example forDate is 30/09/2013 00:00

dayOffset is 8.

I would expect to get 8/10/2013 00:00 but the value I'm getting (not printing) is 7/10/2013 23:00.

Why is that? Does someone have a clue?

EDIT: I just noticed that the first dates that come out well are IDT and after a few days it uses IST. The difference is between "Israel day-light time" and "Israel standard time" which is 1 hour difference.

How do I get over this obstacle?

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
user2328703
  • 227
  • 2
  • 11

1 Answers1

1

Since NSDates have no concept of timezones, and and using a fixed time interval to add 1 day could give you incorrect results, there are 2 two things you need to improve:

NSDate *dateToBeOffset = [NSDate date];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
[dayComponent setDay:8]; //Days you'd like to offset
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *offsetDate = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeOffset options:0];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"EET"]; // Eastern_European_Time
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeZone:timeZone];

NSLog(@"%@", [dateFormatter stringFromDate:offsetDate]);
mmackh
  • 3,550
  • 3
  • 35
  • 51