Converting date of format yyyy-MM-dd'T'HH:mm:ss.SSS

后端 未结 3 1276
梦如初夏
梦如初夏 2021-01-03 09:54

I have few NSDate objects which contain values compliant to this format yyy-MM-dd\'T\'HH:mm:ss.SSS

When I try to convert to a different for

3条回答
  •  独厮守ぢ
    2021-01-03 10:34

    You've got an NSDate, modelObj.createdDate, and you want to format it as a string in a certain format, MMM dd, yyyy HH:mm. You don't need to convert the date to a string and then back to another NSDate and then back to a string again. If you use the same formatter for both operations, you'll just end up with the same date you started with.

    You only need to format the date once, to your final desired appearance:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM dd, yyyy HH:mm"];
    NSLog(@"========= REal Date %@",[format stringFromDate:modelObj.createdDate]);
    

    The NSDate itself is not "compliant to the following format". It has no format -- it's a moment in time, an offset from a reference date. If you NSLog() it, it will indeed format itself into a human-readable string (probably using a date formatter behind the scenes), but that is just one representation that it chooses.

    Right now, you're getting nil from the second formatting operation, NSDate *formattedDate = [format dateFromString:createdDateStr]; because the format of the string you pass in to the formatter has to exactly match what the formatter expects. In this case, it doesn't, because you created the string using the format yyyy-MM-dd'T'HH:mm:ss.SSS, but have told the formatter to expect MMM dd, yyyy HH:mm. The formatter thus can't parse the string, and returns nil to indicate failure.

提交回复
热议问题