Jac*_*ień 6 objective-c nsdate ios
我注意到这NSDate *nowDate = [NSDate date];给了我GMT + 0时间而不是当地时间.所以基本上在我的iPad上是13:00,这段代码的输出是12:00.
我如何正确地获得当地时间?
Raj*_*ana 28
试一试 !
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];//use `[NSTimeZone localTimeZone]` if your users will be changing time-zones.
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
Run Code Online (Sandbox Code Playgroud)
它会根据当前系统时区为您提供时间.
NSDate不关心时区.它只是记录一个时刻.
在使用NSDateFormatter获取日期的字符串表示时,应设置本地时区:
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // Set date and time styles
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateString = [dateFormatter stringFromDate:date];
Run Code Online (Sandbox Code Playgroud)
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
NSDate *d = [calendar dateFromComponents:dateComponents];
Run Code Online (Sandbox Code Playgroud)