我有一个JSON格式的日期字符串,它看起来像这样: 2013-05-22T10:54:40.437
我正在尝试将其转换为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之后的日期是零。有谁知道我在这里做错了什么? 谢谢!
答案 0 :(得分:31)
使用此日期格式:
yyyy-MM-dd'T'HH:mm:ss.SSS
您的代码几乎没有修改:
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”如何在评论中指出,逃避破折号是不必要的。转义已从代码中删除
iOS 11 +更新
ISO8601DateFormatter
是在iOS 10 +上解析互联网日期的推荐方法。
但是,几乎没有问题阻止它使用问题中的特定格式:
+00:00
或Z
表示“祖鲁时间”UTC)如果日期字符串包含毫秒和时区(例如2018-09-07T14:04:13.143Z
),则可以按如下方式使用(Swift示例):
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
答案 1 :(得分:3)
您的日期格式不正确。它应该是:
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:SSS"];
三个首都'S'意味着它将小数部分变为3位数。你可以随意调整它。
答案 2 :(得分:2)
If your date format is "2014-02-25T13:05:10+00:00" then,
your code should be like this....
NSURL *url = [NSURL URLWithString:@"your URL"];
NSString *str = [[NSString alloc] initWithContentsOfURL:url usedEncoding:Nil error:Nil];
NSDateFormatter *dateFor = [[NSDateFormatter alloc] init];
[dateFor setDateFormat:**@"yyyy-MM-dd'T'HH:mm:ss'+'SS:SS"**];
NSDate *yourDate = [dateFor dateFromString:str];
NSLog(@"Your Date: %@",yourDate);
答案 3 :(得分:2)
-(void)viewDidLoad {
self.date = [dateForRFC3339DateTimeString:@"2015-01-18T01:00:00.000Z"];
}
-(NSDate *)dateForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString {
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to a NSDate.
NSDate *result = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
return result;
}