user2813740 user2813740 - 9 days ago 6
iOS Question

NSDateFormatter does not formate date correctly ios10

I am trying to convert date with specific formate and just wanted to get date from passed date as shown below but getting nil
What am I doing wrong?

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSDate *date = [dateFormatter dateFromString: [dicValues valueForKey:@"DateNeeded"]];
[dateFormatter setDateFormat:@"dd/MM/yyyy h:mm a"];
NSString *strSubTitle = [[NSString alloc] initWithFormat:@"%@", [dateFormatter stringFromDate:date]];


Date i am receiving is : 2016-11-17T23:46:50.35 , 2016-11-28T21:25:20.927 and 2016-11-29T00:00:00

Answer

You need to convert

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

to this

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

As in your date string you are receiving MilliSeconds also

Edit

This code is working for me, check the date format which you are getting from server

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    NSDate *date = [dateFormatter dateFromString: @"2016-11-28T21:25:20.927"];
    if (date == nil) {
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
        date = [dateFormatter dateFromString: @"2016-11-28T21:25:20.927"];
    }
    [dateFormatter setDateFormat:@"dd/MM/yyyy h:mm a"];
    NSString *strSubTitle = [[NSString alloc] initWithFormat:@"%@", [dateFormatter stringFromDate:date]];