【问题标题】:NSDateformatter does not format correctlyNSDateformatter 格式不正确
【发布时间】:2013-02-01 01:06:32
【问题描述】:

我的 NSDateformatter 无法正常工作。我的日期是这样的字符串。

2013-02-20 00:00:00

我需要像这样将它作为 NSDate 返回

2013-02-20

我现在得到的是这个。

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

[dateFormat setDateFormat:@"yyyy-MM-dd"];
[dateFormat dateFromString:dateString]

但这不起作用。 有什么帮助吗?

【问题讨论】:

  • 您在从字符串中提取日期之前设置了第二种格式,您没有将提取的日期存储在任何地方,然后您永远不会将日期转换回字符串。 (请注意,NSDate 中不包含任何格式信息。)
  • (基本上,您对自己在做什么一无所知,但您却冒昧地将其归咎于 NSDateFormatter。)
  • “最模糊的想法……”——现在这是我肯定会吸收的短语!
  • @HotLicks,这是一个史诗般的评论。 :)

标签: iphone ios objective-c nsdate nsdateformatter


【解决方案1】:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate* date=[dateFormat dateFromString: dateString];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSLog(@"%@",[dateFormat stringFromDate: date]);

这会起作用 试试看

【讨论】:

  • 如果这条线应该执行多次,这将不会有效。 NSDateFormatters 很昂贵。它们应该以某种方式重复使用。
  • 所有良好的objective-c实践仍然有效。这只是一个解释代码sn-p。每个用户都将根据需要决定如何处理此代码。
  • @RamyAlZuhouri 你的意思是每个体面的用户。我想大多数人只会复制和粘贴这个......
【解决方案2】:

如果您有多个要解析的日期,则值得创建一个输入和一个输出日期格式化程序

static NSDateFormatter *inputDateFormatter;
static NSDateFormatter *outputDateFormatter;
if (!inputDateFormatter) {
    inputDateFormatter= [[NSDateFormatter alloc] init];
    [inputDateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

    outputDateFormatter = [[NSDateFormatter alloc] init];
    [outputDateFormatter setDateFormat:@"yyyy-MM-dd"];
}
NSDate *date = [inputDateFormatter dateFromString:@"2013-02-20 00:00:00"];

NSString *string = [outputDateFormatter stringFromDate:date];

NSLog(@"%@", string);

结果

2013-02-20

由于创建 NSDateFormatter 的成本很高,您应该将它们存储在单例中或将它们声明为静态以便为该方法创建一次。


我需要像这样将它作为 NSDate 返回

日期没有格式,它只是一个时间点。您必须在需要的地方创建一个具有所需格式的字符串。

【讨论】:

  • 留下原来的评论:-1,因为你应该使用一个单一的格式化程序,你让事情变得更难。
  • @RamyAlZuhouri,你能解释一下,为什么它应该是一个单一的格式化程序?
  • 在 OOP 中,如果您需要多次使用一个变量,您可以创建一个类实例变量。如果我不得不使用这段代码 N 次,这正是我会做的,而且我不会使用静态变量。现在这无关紧要,因为我们应该将讨论扩展到整个 OP 类,这不是问题的主题。
  • 一个 ivar 不保证它保持活跃。恳请您继续投票,并否决更多答案。
  • 我可以使用 ARC。所以是的,除非我把代码弄乱了,否则它可以保证保持活力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多