0

浏览了文档后,似乎以下情况应该有效,但结果始终为零。(这适用于 iOS sdk 6)

NSString *releaseDate = @"2012-10-22T00:00:00-07:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date = nil;

[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss-ZZZZZ"];
date = [dateFormatter dateFromString:releaseDate];

NSLog(@"Result date: %@", date); // Logs "(null)"

有什么见解吗?

提前感谢您的帮助。

4

2 回答 2

1

Ok. A bit of re-reading of the docs revealed my misunderstandings:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *releaseDate = @"2012-10-22T00:00:00-07:00";
NSDate *date = nil;

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
date = [dateFormatter dateFromString:releaseDate];

NSLog(@"Result date: %@", date);
NSLog(@"Result string: %@", [dateFormatter stringFromDate:date]);

The "T" had to be enclosed in apostrophes and the "ZZZZZ" for time zone already accounts for the "-" so it had to be removed.

Now it works as expected.

于 2013-01-07T01:36:36.520 回答
1

你试试这个怎么样。如果您的日期字符串像我猜测的那样未本地化,即使 Apple 也建议您可以使用以下内容:

struct tm tmDate;
const char *formatString = "%Y-%m-%dT%H:%M:%S%z";

strptime_l(releaseDate, formatString, & tmDate, NULL);
date = [NSDate dateWithTimeIntervalSince1970: mktime(& tmDate)];

NSLog(@"Result date: %@", date);

不过,您的发布日期必须是 C 字符串,如,const char *releaseDate = "2012-10-22T00:00:00-07:00";您也可以从UTF8String.NSString

于 2013-01-06T01:06:38.777 回答