我如何获得GMT时间?
NSDate *c =[NSDate date];
给出系统时间,而不是GMT。
答案 0 :(得分:9)
这是Ramin答案的简单版本
+ (NSDate *) GMTNow
{
NSDate *sourceDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];
[sourceDate addTimeInterval:currentGMTOffset];
return sourceDate;
}
答案 1 :(得分: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];
答案 2 :(得分:4)
如果执行日期计算,这些类别可能会有用。将您的日期转换为“标准化”(即具有相同的月,日和年但在+1200 UTC),如果您随后使用同样设置为UTC的NSCalendar执行后续计算(+[NSCalendar normalizedCalendar]
),这一切都会成功。
@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
答案 3 :(得分:2)
+ (NSDate*) convertToGMT:(NSDate*)sourceDate
{
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSTimeInterval gmtInterval = [currentTimeZone secondsFromGMTForDate:sourceDate];
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease];
return destinationDate;
}
答案 4 :(得分:0)
NSDate在内部存储时区 - 如果你想要一个日期的字符串表示,你可以调用并传入目标时区的一些函数,参见apple's documentation
答案 5 :(得分:0)
答案 6 :(得分:-3)
- (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;
}