代码之家  ›  专栏  ›  技术社区  ›  Mick Walker

NSDate-iPhone上的GMT

  •  3
  • Mick Walker  · 技术社区  · 16 年前

    我在生产应用程序中有以下代码,该应用程序从用户输入的日期开始计算GMT日期:

    NSDate *localDate = pickedDate;
        NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
        NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
        NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
    

    这项法规运行良好,直到令人恐惧的夏令时间上周在英国生效。

    如何将日期转换为GMT,同时考虑日光节约?

    1 回复  |  直到 16 年前
        1
  •  6
  •   Jason Coco superfell    16 年前

    nsdate使用与绝对值的偏移量来表示时间间隔。基础是以GMT为单位,所有时间间隔都以GMT为单位,这就是为什么您会看到差异。如果需要日期的字符串表示形式(例如存储在数据库或其他地方),请使用nsdateformatter在需要的特定时区中创建它。

    因此,这将始终为您提供GMT格式的日期的字符串表示(类似于存储在MySQL中)(考虑到白光节约时间):

    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // e.g., set for mysql date strings
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    NSString* mysqlGMTString = [formatter stringFromDate:[NSDate date]];
    

    这将为您提供正确的GMT时间日期字符串,而不考虑本地时区。另外,请记住,使用nsdate和time interval进行的所有相对测量都以gmt为基础。当您向用户演示或需要进行日历计算时(例如,显示一个警告你的订阅将于明天到期)。

    编辑:我忘记加时区了!没有它,格式化程序将使用系统时区。