我如何获得GMT时间?
NSDate *c =[NSDate date];
Run Code Online (Sandbox Code Playgroud)
给出系统时间,而不是GMT.
这是Ramin答案的简单版本
+ (NSDate *) GMTNow
{
NSDate *sourceDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];
[sourceDate addTimeInterval:currentGMTOffset];
return sourceDate;
}
Run Code Online (Sandbox Code Playgroud)
如果它是出于显示目的而想要显示它,请使用NSDateFormatter,如下所示:
NSDate *myDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
// Set date style:
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *GMTDateString = [dateFormatter stringFromDate: myDate];
Run Code Online (Sandbox Code Playgroud)
Ram*_*min -4
- (NSDate*) convertToUTC:(NSDate*)sourceDate
{
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease];
return destinationDate;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17385 次 |
| 最近记录: |