0

我有以下内容NSString

NSString * dateString = @"2012-01-24T14:59:01Z";

我想NSDate从该字符串创建一个。我查找了NSDate类参考并考虑使用dateWithNaturalLanguageString:

创建并返回一个NSDate对象,该对象设置为给定字符串指定的日期和时间。

+ (id)dateWithNaturalLanguageString:(NSString *)string

参数 string 一个字符串,其中包含日期的通俗化规范,例如“last Tuesday at Dinner”、“3pm December 31, 2001”、“12/31/01”或“31/12/01”。 返回值NSDate设置为字符串指定的当前日期和时间 的新对象。

但是,当我尝试像这样使用它时:

NSDate * date = [NSDate dateWithNaturalLanguageString:dateString];

我收到以下错误:

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

4

4 回答 4

4

NSDateFormatter 类将帮助您解决这个问题。并且已经有很多关于这个的问题,例如,这里是第一个:Convert NSString->NSDate?

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

于 2012-01-24T16:05:07.190 回答
1

尝试使用构造函数构造dateWithString函数,或者(如果这给您带来类似的错误),尝试使用此处NSDateFormatter描述的 an 。

于 2012-01-24T16:06:28.487 回答
1

该类dateWithNaturalLanguageString:方法仅在 Mac OS X 上实现,而不在 iOS 上实现,这就是您收到错误的原因。

为了实现你正在寻找的东西,你需要这个NSDateFormatter类。该课程非常繁重,因此您需要先阅读文档以了解如何最好地使用它。

于 2012-01-24T16:07:20.250 回答
1

在这里找到了我想要的东西。这是一个 RFC 3339 日期时间。

- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString
    // Returns a user-visible date time string that corresponds to the
    // specified RFC 3339 date time string. Note that this does not handle
    // all possible RFC 3339 date time strings, just one of the most common
    // styles.
{
    NSString *          userVisibleDateTimeString;
    NSDateFormatter *   rfc3339DateFormatter;
    NSLocale *          enUSPOSIXLocale;
    NSDate *            date;
    NSDateFormatter *   userVisibleDateFormatter;

    userVisibleDateTimeString = nil;

    // Convert the RFC 3339 date time string to an NSDate.

    rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease];

    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];

    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
    if (date != nil) {

        // Convert the NSDate to a user-visible date string.

        userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        assert(userVisibleDateFormatter != nil);

        [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
        [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];

        userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
    }
    return userVisibleDateTimeString;
}
于 2012-01-24T16:18:00.867 回答