从日期字符串获取时区偏移量
Getting timezone offset from a date string
我将以下日期作为字符串:2015-04-18T08:35:00.000+03:00,我想以秒为单位获取与 GMT 的偏移量,即 10800。
我可以用“+”字符拆分日期字符串,得到一个字符串 xy:ab,然后使用公式 xy*3600 + a*60 + b.
计算偏移量
有没有更好的方法来实现我所需要的,例如使用 NSDate 和 NSDateFormatter?
我终于使用了这段代码:
NSString *dateStringWithTZ = @"2015-04-18T08:35:00.000+03:00";
// Create date object using the timezone from the input string.
NSDateFormatter *dateFormatterWithTZ = [[NSDateFormatter alloc] init];
dateFormatterWithTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSDate *dateWithTZ = [dateFormatterWithTZ dateFromString:dateStringWithTZ];
// Cut off the timezone and create date object using GMT timezone.
NSString *dateStringWithoutTZ = [dateStringWithTZ substringWithRange:NSMakeRange(0, 23)];
NSDateFormatter *dateFormatterWithoutTZ = [[NSDateFormatter alloc] init];
dateFormatterWithoutTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
dateFormatterWithoutTZ.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *dateWithoutTZ = [dateFormatterWithoutTZ dateFromString:dateStringWithoutTZ];
// Calculate the difference.
NSInteger difference = [dateWithoutTZ timeIntervalSinceReferenceDate] - [dateWithTZ timeIntervalSinceReferenceDate];
return [NSNumber numberWithInteger:difference];
我将以下日期作为字符串:2015-04-18T08:35:00.000+03:00,我想以秒为单位获取与 GMT 的偏移量,即 10800。
我可以用“+”字符拆分日期字符串,得到一个字符串 xy:ab,然后使用公式 xy*3600 + a*60 + b.
计算偏移量有没有更好的方法来实现我所需要的,例如使用 NSDate 和 NSDateFormatter?
我终于使用了这段代码:
NSString *dateStringWithTZ = @"2015-04-18T08:35:00.000+03:00";
// Create date object using the timezone from the input string.
NSDateFormatter *dateFormatterWithTZ = [[NSDateFormatter alloc] init];
dateFormatterWithTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSDate *dateWithTZ = [dateFormatterWithTZ dateFromString:dateStringWithTZ];
// Cut off the timezone and create date object using GMT timezone.
NSString *dateStringWithoutTZ = [dateStringWithTZ substringWithRange:NSMakeRange(0, 23)];
NSDateFormatter *dateFormatterWithoutTZ = [[NSDateFormatter alloc] init];
dateFormatterWithoutTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
dateFormatterWithoutTZ.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *dateWithoutTZ = [dateFormatterWithoutTZ dateFromString:dateStringWithoutTZ];
// Calculate the difference.
NSInteger difference = [dateWithoutTZ timeIntervalSinceReferenceDate] - [dateWithTZ timeIntervalSinceReferenceDate];
return [NSNumber numberWithInteger:difference];