【问题标题】:How to init a NSDate with a NSString? [duplicate]如何用 NSString 初始化 NSDate? [复制]
【发布时间】:2012-05-29 10:30:02
【问题描述】:

可能重复:
Converting NSString to NSDate (and back again)

我还是 obj-C/iOS 开发的初学者...我创建了一个包含 NSDate *date 的类,并从 XML 文件中获取数据。所以我想做这样的事情:

[myItem setDate:[NSDate dateWithString:xmlDate]];

我得到错误:

选择器“dateWithString:”没有已知的类方法

最好的方法是什么?谢谢

【问题讨论】:

    标签: objective-c nsdate


    【解决方案1】:

    您需要NSDateFormatter。有关详细信息,请参阅 this previous questionthis previous questionthis previous question 或仅 Apple Date Formatter guide

    请记住在发帖前搜索重复的问题。

    【讨论】:

      【解决方案2】:

      我建议您为此使用 NSDateFormatter 实例:

      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      // set the appropriate format in this string
      [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
      NSDate *date = [dateFormatter dateFromString:xmlDate];
      [dateFormatter release];
      

      【讨论】:

        【解决方案3】:

        要从NSString 生成NSDate 对象,您应该使用NSDateFormatter。更多信息可以在 Apple 的网站上找到:

        https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-23
          相关资源
          最近更新 更多