NSDateFormatter返回nil

问题描述:

我正在尝试解析以以下格式传递的日期:

I'm trying to parse a date passed in the format:

"2014-03-26T05:07:42.14286Z"

我的NSDateFormatter代码看起来像这样

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'SS'Z'"];
self.createdAt = [dateFormatter dateFromString:@""2014-03-26T05:07:42.14286Z""];

但是它只返回nil.我已经尝试了带有或不带有刻度的多种变体,但是我似乎缺少了一些东西.我是否错误地使用了NSDateFormatter,误解了刻度线或其他东西的用法?

But it just returns nil. I've tried multiple variations with and without the ticks but I seem to be missing something. Am I using NSDateFormatter incorrectly, misunderstanding the usage of ticks or something else entirely?

如果给定的字符串与预期格式不符,则格式化程序将返回nil.您的格式字符串几乎正确,您只需要:

The formatter returns nil if the given string doesn't correspond to the expected format. Your format string was almost right, you just needed to :

  • 撇号应仅用于文字
  • 应将毫秒指定为"SSS"并匹配间隔(使用ss.SSS)

正确的格式字符串是:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *d = [df dateFromString:@"2014-03-26T05:07:42.14286Z"];