NSDate问题的JSON日期 [英] JSON date to NSDate Issue
问题描述
我有一个JSON格式的日期字符串,它看起来像这样: 2013-05-22T10:54:40.437
I have a date string in JSON format, it looks like this: 2013-05-22T10:54:40.437
我正在尝试将其转换为NSDate.
And I'm trying to convert it to NSDate.
- (NSString *)dateFromString:(NSString *)datestring{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
NSDate *date = [dateFormat dateFromString:datestring];
//date is nil here.
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date -- %@",datestring);
return newString;
}
但是dateFromString之后的日期为nil.有人知道我在这里做错了吗? 谢谢!
But date is nil after dateFromString. Does anyone know what I did wrong here? Thanks!
推荐答案
使用此日期格式:
yyyy-MM-dd'T'HH:mm:ss.SSS
您的代码几乎没有修改:
Your code with little modification:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [dateFormat dateFromString:datestring];
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(@"Date: %@, formatted date: %@", date, newString);
将以下输出提供给我:
Date: 2013-05-22 08:54:40 +0000, formatted date: 05/22/2013
如何在评论中指出"ikinci viking"是如何避免破折号的.转义已从代码中删除
how "ikinci viking" pointed out in comment, escaping the dashes is unnecessary. Escaping removed from the code
针对iOS 11+的更新
ISO8601DateFormatter
是在iOS 10+上解析互联网日期的推荐方法.
ISO8601DateFormatter
is the recommended way to parse internet date on iOS 10+.
但是,它几乎没有问题,无法将其与问题中的特定格式一起使用:
However it has few issues preventing it from usage with the specific format from the question:
- 毫秒仅在iOS 11+上受支持
- 它不适用于没有时区的日期(有问题的情况).日期字符串必须包含时区部分(例如,"Zulu时间" UTC的
+00:00
或Z
)
如果日期字符串同时包含毫秒和时区(例如2018-09-07T14:04:13.143Z
),则可以按以下方式使用它(以Swift为例):
If date strings contains both milliseconds and timezone (e.g. 2018-09-07T14:04:13.143Z
), it can be used as follows (Swift example):
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
这篇关于NSDate问题的JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!