JSON date to NSDate Issue

我与影子孤独终老i 提交于 2019-11-30 06:59:39

Use this date format:

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);

gives me this output:

Date: 2013-05-22 08:54:40 +0000, formatted date: 05/22/2013

Edit: how "ikinci viking" pointed out in comment, escaping the dashes is unnecessary. Escaping removed from the code


Update for iOS 11+

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:

  • Milliseconds are supported only on iOS 11+
  • It does not work for dates without timezone (the case in question). Date string must contain timezone part (e.g. +00:00 or Z for "Zulu time" UTC)

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]

Your date format is incorrect. It should be:

[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:SSS"];

The three capital 'S' means it will take the fractional part to 3 digits. Adjust it as you will.

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);
-(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;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!