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 format such as MMM dd, yyyy HH:mm the formatter always returns nil.
However, if I hardcode the string value I get through the NSDate object , it is transformed to the new format without a problem.
I populate my NSDate object in the model using the setValue:forKey: method, and I feel the problem is here where the JSON library passes a string value. However, the debugging shows that the NSDate has contains the value returned via JSON.
Any idea what’s causing this strange behavior?
This is my conversion code:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSString *createdDateStr = [format stringFromDate:modelObj.createdDate];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];
NSDate *formattedDate = [format dateFromString:createdDateStr];
NSLog(@"========= REal Date %@",[format stringFromDate:formattedDate]);
EDIT: Rereading your question, I think you’ve got a conceptual misunderstanding aside from anything else:
As far as I’m aware (I’m not an Objective-C programmer, admittedly) an
NSDateobject doesn’t know anything about formatting. It just represents an instant in time. It isn’t aware of whether it was parsed from text or created in some other way.It’s like an
int– anintvariable isn’t in decimal or hex, it’s just a number. It’s when you format and parse that you specify that. Likewise, you useNSDateFormatterto describe the format you want at the point of parsing and formatting.You’ve currently only got one
NSDateFormatter– you’re setting the format to"yyyy-MM-dd'T'HH:mm:ss.SSS"then resetting it before you’ve calleddateFromString. The code snippet you’ve given formatsmodelObj.createdDateinto ISO-8601 format, but then tries to parse it using the “MMM dd, yyyy HH:mm” format.I suggest you have two separate
NSDateFormatterobjects:Note that I’ve changed your
formattedDatevariable toparsedDate, as that’s what it really is – anNSDatewhich has been created by parsing text.As noted in comments, unless you actually need to format and parse like this, you shouldn’t. I included all of your original code just to show how you can format a date and then reparse it with the same
NSDateFormatter. You’ll get the same result with just:In general, you should avoid unnecessary conversions. Convert from text to the more natural data type (
NSDatein this case, but the same applies for numbers etc) and use that data type for as much of your code as possible, only converting to text at the last moment.