【问题标题】:objective-c - NSDateFormatter returns wrong dateobjective-c - NSDateFormatter 返回错误的日期
【发布时间】:2012-03-23 14:38:14
【问题描述】:

我有这段代码:

 // Convert string to date object
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"MMMM d, YYYY"];
        NSDate *formatDate = [dateFormat dateFromString:self.date];
        NSLog(@"1-%@", self.date);
        NSLog(@"2-%@", formatDate);
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:formatDate];
        NSString *dateCal = [NSString stringWithFormat:@"%d/%d/%d", [components day], [components month], [components year]];
        NSLog(@"3-%@", dateCal);
        milage.date = dateCal;

第一个 NSLog 返回:

2012 年 1 月 1 日至 3 月 23 日

第二个:

2-2011-12-25 00:00:00 +0000

第三个:

3-25/12/2011

为什么从字符串中获取日期并格式化后日期会改变?我期待第三个 NSLog(或 dateCal)等于 23/3/2012。我住在英国,所以与时区无关..

谢谢,

杰克

【问题讨论】:

  • 我很惊讶您在 NSLog self.date 时看到“2012 年 3 月 23 日”。在我的机器上, NSLog(@"%@", [NSDate date]);产生类似“2012-03-23 14:47:48 +0000”的日期。
  • 谢谢,只需要改用'yyyy'..
  • 这里做个测试,看看这个条件是否成立 [self.date timeIntervalSinceReferenceDate] == [formatDate timeIntervalSinceReferenceDate]。 (丑陋的格式,抱歉,但由于这不是一个真正的答案,我认为它应该是一个评论)。
  • @danh self.date 是一个字符串。
  • 它是一个字符串,但是当我使用小写字母 'yyyy' 而不是 'YYYY' 时,为什么我的代码可以工作?

标签: iphone objective-c ios date nsdateformatter


【解决方案1】:

需要在行中使用小写'y':

[dateFormat setDateFormat:@"MMMM d, YYYY"];

【讨论】:

  • 为什么大写的YYYY会导致错误的年份?
【解决方案2】:

你用过setLocale方法吗?

另外,来自技术问答:

如果您使用的是用户可见的日期,则应避免设置日期格式字符串,因为很难预测格式字符串在所有可能的用户配置中的表达方式。相反,您应该尝试限制自己设置日期和时间样式(通过 -[NSDateFormatter setDateStyle:] 和 -[NSDateFormatter setTimeStyle:])。

【讨论】:

    【解决方案3】:

    使用[dateFormat setDateStyle:NSDateFormatterLongStyle];
    而不是[dateFormat setDateFormat:@"MMMM d, YYYY"];
    我一找到理由就给你理由。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多