我只是注意到这NSDate *nowDate = [NSDate date];
给了我 GMT+0 时间,而不是当地时间。所以基本上在我的 iPad 上是 13:00,这段代码的输出是 12:00。
如何正确获取当地时间?
我只是注意到这NSDate *nowDate = [NSDate date];
给了我 GMT+0 时间,而不是当地时间。所以基本上在我的 iPad 上是 13:00,这段代码的输出是 12:00。
如何正确获取当地时间?
试一试 !
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];
它将根据当前系统时区为您提供时间。
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];
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];
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(@"%@",currentTime);