【问题标题】:Getting timezone offset from a date string从日期字符串获取时区偏移量
【发布时间】:2015-06-04 12:27:10
【问题描述】:

我有以下日期作为字符串:2015-04-18T08:35:00.000+03:00,我想以秒为单位获得与 GMT 的偏移量,即 10800。

我可以用'+'字符分割日期字符串,有一个字符串xy:ab,然后用公式xy*3600 + a*60 + b计算偏移量。

有没有更好的方法来实现我的需要,例如使用 NSDate 和 NSDateFormatter?

【问题讨论】:

  • 使用NSDateFormatter
  • 这是一个很好的观点,但问题是我不知道怎么做。我可以创建一个 NSDateFormatter 实例并设置日期格式 yyyy-MM-dd'T'HH:mm:ss.SSSZ。但是那我怎样才能得到我想要的号码呢?

标签: objective-c nsdate nsdateformatter


【解决方案1】:

我终于使用了这段代码:

    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];

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2018-03-15
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多