从 NSString 创建 NSDate
我有以下 NSString
:
NSString * dateString = @"2012-01-24T14:59:01Z";
我想从该字符串创建一个 NSDate
。我查找了 NSDate
类参考并想到使用 dateWithNaturalLanguageString:
:
创建并返回设置为日期和时间的
NSDate
对象 由给定字符串指定。
+ (id)dateWithNaturalLanguageString:(NSString *)string
参数 字符串 包含日期的口语规范的字符串, 例如“上周二晚餐”、“2001 年 12 月 31 日下午 3 点”、“12/31/01” 或“2001 年 12 月 31 日”。 返回值 设置为当前的新
NSDate
对象 由字符串指定的日期和时间。
但是,当我尝试像这样使用它时:
NSDate * date = [NSDate dateWithNaturalLanguageString:dateString];
我收到以下错误:
选择器“dateWithNaturalLanguageString:”没有已知的类方法
I have the following NSString
:
NSString * dateString = @"2012-01-24T14:59:01Z";
I want to create an NSDate
from that string. I looked up the NSDate
Class Reference and thought of using dateWithNaturalLanguageString:
:
Creates and returns an
NSDate
object set to the date and time
specified by a given string.
+ (id)dateWithNaturalLanguageString:(NSString *)string
Parameters
string
A string that contains a colloquial specification of a date,
such as “last Tuesday at dinner,” “3pm December 31, 2001,” “12/31/01,”
or “31/12/01.”
Return Value
A newNSDate
object set to the current
date and time specified by string.
However, when I'm trying to use it like this:
NSDate * date = [NSDate dateWithNaturalLanguageString:dateString];
I'm getting the following error:
No known class method for selector 'dateWithNaturalLanguageString:'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSDateFormatter 类将帮助您解决这个问题。已经有很多关于此的问题,例如,这是第一个: Convert NSString->NSDate?< /一>
<一href="http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html" rel="nofollow noreferrer">http://developer.apple .com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
NSDateFormatter class will help you with this problem. And there are many questions about this already, for example, here is the first one: Convert NSString->NSDate?
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
尝试使用构造函数
dateWithString
构造函数,或者(如果这给您带来类似的错误),请尝试使用NSDateFormatter
,如 此处。Try using the constructor
dateWithString
constructor or (if that gives you a similar error), try using anNSDateFormatter
as described here.dateWithNaturalLanguageString:
类方法仅在 Mac OS X 上实现,而不在 iOS 上实现,这就是您收到错误的原因。为了实现您正在寻找的目标,您需要 NSDateFormatter 类。该类非常繁重,因此您需要先阅读文档以了解如何最好地使用它。
The
dateWithNaturalLanguageString:
class method is only implemented on Mac OS X, not on iOS, that is why you're getting the error.To achieve what you're looking for, you need the
NSDateFormatter
class. The class is quite heavy, so you'll want to read the documentation first to understand how best to use it.找到了我正在寻找的内容 此处。这是 RFC 3339 日期时间。
Found exactly what I was looking for here. It's an RFC 3339 date-time.