Return 时区的 GMT 偏移量,包括夏令时

Return GMT offset of timezone including daylight saving

我目前正在尝试 return 时区的偏移量作为 NSString。 目前我正在这样做:

NSDateFormatter *df = [NSDateFormatter new];

[df setDateFormat:@"dd/MM/yyyy HH:mm"];

//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *timezoneStr = [NSString stringWithFormat:@"%@", df.timeZone];

NSLog(@"date = %@", timezoneStr);

//returns 
//GMT-0500 (GMT-5) offset -18000

我想做的是return只是:

-5

但是,我想知道是否有一种简单的方法可以在不解析字符串并获取值的情况下访问此数字。

此外,作为附带问题,上面的代码是否考虑了 +/- 夏令时?

如果您想要本地时区的 UTC 偏移量(以小时为单位),您可以使用以下内容:

-(NSString *) UTCOffset {
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    float offset = localTZ.secondsFromGMT/3600.0;
    return [NSString stringWithFormat:@"%g",offset];
}

如果夏令时当前有效,则返回值将包括任何夏令时偏移量。具体来说,当 DST 生效时,本地时区更改为标准时区的 "DST equivalent"。例如我的时区从 "Australian Eastern Standard Time (UTC+10)" 更改为 "Australian Eastern Summer Time (UTC+11)"。

另请注意,某些时区与 UTC(30 分钟)有小数小时差异,因此整数值不够