NSDate independent of timezone?

后端 未结 5 535
萌比男神i
萌比男神i 2020-12-17 22:45

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?

5条回答
  •  悲哀的现实
    2020-12-17 23:18

    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
    

提交回复
热议问题