我如何获得GMT时间?

NSDate *c =[NSDate date];

为系统时间,而不是GMT。

有帮助吗?

解决方案

- (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;
}

其他提示

这是拉敏的回答的一个简化版本

+ (NSDate *) GMTNow
{ 
 NSDate *sourceDate = [NSDate date];
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];

    [sourceDate addTimeInterval:currentGMTOffset];

    return sourceDate;
}

如果这是为了显示你想要显示它,使用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];

如果执行日期计算,这些类别可以是有用的。已经转换你的日期是“规范化”(即,具有相同的月,日和年,但在+ 1200 UTC),如果再使用NSCalendar,它也设定为UTC(+[NSCalendar normalizedCalendar]),这是进行后续计算LL所有锻炼。

@implementation NSDate (NormalizedAdditions)

+ (NSDate *)normalizedDateFromDateInCurrentCalendar:(NSDate *)inDate
{
    NSDateComponents *todayComponents = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                                                        fromDate:inDate];
    [todayComponents setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [todayComponents setHour:12];

    return [[NSCalendar normalizedCalendar] dateFromComponents:todayComponents];
}

+ (NSDate *)normalizedDate
{
    return [self normalizedDateFromDateInCurrentCalendar:[NSDate date]];
}

@end

@implementation NSCalendar (NormalizedAdditions)

+ (NSCalendar *)normalizedCalendar
{
    static NSCalendar *gregorian = nil;
    if (!gregorian) {
        gregorian = [[NSCalendar alloc]
                     initWithCalendarIdentifier:NSGregorianCalendar];
        [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];   
    }
    return gregorian;
}

@end
+ (NSDate*) convertToGMT:(NSDate*)sourceDate
{
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];

    NSTimeInterval gmtInterval = [currentTimeZone secondsFromGMTForDate:sourceDate];

    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease];     
    return destinationDate;
}

NSDate的内部存储时区 - 有你可以打电话和传中的目标时区,如果你仅仅指刚想要的日期的字符串表示的一些功能,看到的苹果的文档

请参阅:

CFTimeZoneCreateWithTimeIntervalFromGMT secondsFromGMT

日期和时间编程指南

scroll top