My Input String is
NSString *inputString=@"15 February 2012 17:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMMM YYYY HH:mm"];
NSDate *dateVal = [dateFormat dateFromString:inputString];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"MM/dd/YYYY HH:mm"];
NSString *outputString = [dateFormat2 stringFromDate:dateVal];
[dateFormat release];
[dateFormat2 release];
I got the following date outputString=12/25/2011 17:05
But it should be 02/15/2012 17:05..Where did i do the mistake?
You are using wrong format for date format and also there is no need to create another instance of NSDateFormatter -
NSString *inputString=@"15 February 2012 17:05";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd MMMM yyyy HH:mm"];
NSDate *dateVal = [dateFormat dateFromString:inputString];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"];
NSString *outputString = [dateFormat stringFromDate:dateVal];
The date format is incorrect, use:
[dateFormat setDateFormat:@"dd MMMM yyyy HH:mm"];
Capital "YYYY" is for use in "Week of Year" based calendars.
See: unicode Date_Format_Patterns
BTW, an NSLog
of dateVal
would have shown that the problem was on the input formatting.
Does your locale correspond to the format you are trying to parse? By default NSDateFormatter uses current locale.
The input date format should be:
[dateFormat setDateFormat:@"dd MMMM yyyy HH:mm"];
来源:https://stackoverflow.com/questions/9294545/how-can-i-convert-the-string-to-date-and-date-from-string