Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate independent of timezone?

I have an app that displays a timetable of certain ferry trips.

If I travel to a different timezone - say 4 hours behind, a 10am ferry trip now shows up as 6am?

I know this has got to do with how dates are treated based on their timezones, but I can't work out how to change that behaviour.

At the moment here's how I am getting the date and displaying it on a UILabel:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
[self.departureTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"departureTime"]]];
[self.arrivalTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"arrivalTime"]]];
[dateFormatter release];

Thanks in advance for your help.

like image 230
Rog Avatar asked Oct 11 '11 00:10

Rog


3 Answers

You'll need to store the timezone that the ferry ride is taking place in and format it for that timezone.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"]; 

NSDate *now = [NSDate date];   
NSLog(@"now:%@", [dateFormatter stringFromDate:now]);

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)];     
[dateFormatter setTimeZone:timeZone];
NSLog(@"adjusted for timezone: %@", [dateFormatter stringFromDate:now]);

Outputs:

2011-10-10 20:42:23.781 Craplet[2926:707] now:20:42
2011-10-10 20:42:23.782 Craplet[2926:707] adjusted for timezone: 16:42
like image 67
bryanmac Avatar answered Nov 07 '22 10:11

bryanmac


You have seen NSDateFormatter's setTimeZone method, yes?

http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDateFormatter/setTimeZone:

(b.t.w., I'd be amazed if there was a ferry that involved crossing four time zones; sounds like a cruise ship itinerary to me)

like image 37
Michael Dautermann Avatar answered Nov 07 '22 11:11

Michael Dautermann


You can also use the NSDateComponents class as described by apple's reference:

If you need to create a date that is independent of timezone, you can store the date as an NSDateComponents object—as long as you store some reference to the corresponding calendar.

In iOS, NSDateComponents objects can contain a calendar, a timezone, and a date object. You can therefore store the calendar along with the components. If you use the date method of the NSDateComponents class to access the date, make sure that the associated timezone is up-to-date.

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html#//apple_ref/doc/uid/20000185-SW1

like image 1
cohen72 Avatar answered Nov 07 '22 09:11

cohen72