如何获得 GMT 时间?
NSDate *c =[NSDate date];
给出系统时间,而不是 GMT。
这是拉明答案的简单版本
+ (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)之后,如果您随后使用也设置为 UTC ( +[NSCalendar normalizedCalendar]
) 的 NSCalendar 执行后续计算,它将一切都解决了。
@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 在内部存储时区——如果您想要日期的字符串表示形式,您可以调用一些函数并传入目标时区,请参阅苹果的文档
- (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;
}