【问题标题】:NSTimeZone timeZoneWithName: works not properlyNSTimeZone timeZoneWithName:工作不正常
【发布时间】:2013-09-14 00:32:21
【问题描述】:

服务器返回正确的日期和时间。纽约时区。

2013-09-10 05:37:07 +0000(发表评论的正确时间)

这是我在应用程序中的格式:

[format setDateFormat:@"dd MMM, yyyy HH:mm"];

[format setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];

结果我得到了

10 sept, 2013 01:37

怎么了?

UPD

代码

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    [format setDateFormat:@"dd MMM, yyyy HH:mm"];

    NSString *stringDate = [format stringFromDate:Date]; //Date is "2013-09-10 05:37:07 +0000"
    //stringDate is "10 sept, 2013 01:37"

【问题讨论】:

    标签: iphone ios timezone


    【解决方案1】:

    我当前的时间(当时)是:下午 3:00

    纽约的时间(当时)是:上午 8:00

    解决办法:

    NSDate *date = activityDate; // Server sends me the date: 2013-09-10 09:00:00 +0000
    NSString *dateFormat = @"dd MMM, yyyy HH:mm";
    //Then the transformation comes here
    NSDateFormatter* newYorkDf = [[NSDateFormatter alloc] init];
    [newYorkDf setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    [newYorkDf setDateFormat:dateFormat];
    
    NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
    [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [gmtDf setDateFormat:dateFormat];
    NSDate *gmtDate = [gmtDf dateFromString:[newYorkDf stringFromDate:date]];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:dateFormat];
    NSString *stringDate1 = [format stringFromDate:gmtDate];
    self.labelDate.text = stringDate1;   // Returns me: 10 Sept, 2013 8:00
    

    【讨论】:

      【解决方案2】:

      您说“服务器返回”。你能告诉我们更多关于你是如何得到你的原始日期的吗? 您可能正在构建一个 UTC 日期,然后将其格式化为 NY(东部时区)日期。复活节 TZ 是 UTC-5。我猜你有夏令时,因为 5:37 - 5h 会给出 0:37。

      如果您发布如何使用显示的代码构建原始日期,我可能会更具体。

      【讨论】:

      • 感谢您的回复!实际上,sarver-side-man 告诉他,他建立了 UTC 日期。
      • 但是当我设置 timeZoneWithAbbreviation:@"UTC" - 与纽约的差异是 6 小时(应该是 7)
      • 问题在于如何在代码中构建Date(最好使用小写字母)变量。我们看不到。如果您通过假设它是 UTC 来构建它,那么格式化程序通过将其移回 4 小时来正确地完成它的工作。换句话说...... 5:45 UTC 确定了一个时刻,无论它发生在世界的哪个地方(或者实际上是宇宙,因此得名)。在那一刻,如果您想知道纽约的时间,格式化程序会为您提供 1:45。如果你问现在在巴黎几点钟,你可能会得到 6 点 45 分。问题是在那之前......当你创建Date 变量时。
      • 我想说的是错误在服务器端。如果他们向您返回一个像“2013-09-10 05:37:07 +0000”这样的字符串并且他们声称这是纽约时间,那么这是他们的错。最后的 +0000 表明应该是 UTC 时间。
      • 所以...要么服务器返回错误的时间,他们将时钟设置为本地时间,但使用 UTC 作为他们的时区,或者他们设置正确,并且他们的输出在世界标准时间。如果是这种情况,那么您的代码就会给您正确的答案。
      猜你喜欢
      • 1970-01-01
      • 2012-05-10
      • 2020-04-23
      • 2023-04-10
      • 2015-01-16
      • 1970-01-01
      • 2016-08-02
      • 2020-02-18
      • 2013-01-22
      相关资源
      最近更新 更多