NSDate independent of timezone?

跟風遠走 提交于 2019-11-29 06:52:56

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

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)

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

Don't confuse an NSDate value with a formatted output like NSLog. NSDate is GMT, Apple's docs:

The sole primitive method of NSDate, timeIntervalSinceReferenceDate, provides the basis for all the other methods in the NSDate interface. This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT.

NSTimeInterval referenceInterval = [[dateFormatter dateFromString:@"1 January 2001 GMT"] timeIntervalSinceReferenceDate];
NSLog(@"referenceInterval: %f", referenceInterval);

NSTimeInterval estInterval = [[dateFormatter dateFromString:@"1 January 2001 EST"] timeIntervalSinceReferenceDate];
NSLog(@"estInterval:       %f", estInterval);

Output:

referenceInterval: 0.000000  
estInterval:   18000.000000
        NSDate *currentDateTime =  datePicker.date;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"EEE,MM-dd-yyyy HH:mm:ss"];
        NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
        NSLog(@"%@", dateInStringFormated);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!