如何在iOS上获取本地时间
我刚注意到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];
// get current date/time NSDate *today = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // display in 12HR/24HR (ie 11:25PM or 23:25) format according to User Settings [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; NSString *currentTime = [dateFormatter stringFromDate:today]; [dateFormatter release]; NSLog(@"%@",currentTime);
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];