GMT在iPhone上的时间

g.r*_*ion 8 iphone nsdate

我如何获得GMT时间?

NSDate *c =[NSDate date];
Run Code Online (Sandbox Code Playgroud)

给出系统时间,而不是GMT.

Chr*_*ris 9

这是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)


Bar*_*ley 8

如果它是出于显示目的而想要显示它,请使用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)

  • 这个答案是错误的。NSDate 对象代表单个时刻。他们不关心时区。仅当您格式化和显示日期时,时区才会发挥作用。修改 NSDate 对象意味着您正在修改它所代表的时间点。 (6认同)
  • -1 这种“NSDate”到“NSDate”的转换具有误导性,并且基于对“NSDate”对象所代表的内容的误解。 (2认同)