There are no direct way to get this. However there is a work around like this which will work in most of the cases. All you have to do is to add all the possible date formatter to the below dateFormatterList
.
- (NSString *)dateStringFromString:(NSString *)sourceString destinationFormat:(NSString *)destinationFormat {
NSString *convertedDateString = nil;
NSArray *dateFormatterList = [NSArray arrayWithObjects:@"yyyy-MM-dd'T'HH:mm:ss'Z'", @"yyyy-MM-dd'T'HH:mm:ssZ",
@"yyyy-MM-dd'T'HH:mm:ss", @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
@"yyyy-MM-dd'T'HH:mm:ss.SSSZ", @"yyyy-MM-dd HH:mm:ss",
@"MM/dd/yyyy HH:mm:ss", @"MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
@"MM/dd/yyyy'T'HH:mm:ss.SSSZ", @"MM/dd/yyyy'T'HH:mm:ss.SSS",
@"MM/dd/yyyy'T'HH:mm:ssZ", @"MM/dd/yyyy'T'HH:mm:ss",
@"yyyy:MM:dd HH:mm:ss", @"yyyyMMdd", @"dd-MM-yyyy",
@"dd/MM/yyyy", @"yyyy-MM-dd", @"yyyy/MM/dd",
@"dd MMMM yyyy", @"MMddyyyy", @"MM/dd/yyyy",
@"MM-dd-yyyy", @"d'st' MMMM yyyy",
@"d'nd' MMMM yyyy", @"d'rd' MMMM yyyy",
@"d'th' MMMM yyyy", @"d'st' MMM yyyy",
@"d'nd' MMM yyyy", @"d'rd' MMM yyyy",
@"d'th' MMM yyyy", @"d'st' MMMM",
@"d'nd' MMMM", @"d'rd' MMMM",
@"d'th' MMMM", @"d'st' MMM",
@"d'nd' MMM", @"d'rd' MMM",
@"d'th' MMM", @"MMMM, yyyy",
@"MMMM yyyy", nil];
//sourceString = @"20/11/2012";
//destinationFormat = @"dd MMMM yyyy";
if (sourceString) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
for (NSString *dateFormatterString in dateFormatterList) {
[dateFormatter setDateFormat:dateFormatterString];
NSDate *originalDate = [dateFormatter dateFromString:sourceString];
if (originalDate) {
[dateFormatter setDateFormat:destinationFormat];
convertedDateString = [dateFormatter stringFromDate:originalDate];
NSLog(@"Converted date String is %@", convertedDateString);
break;
}
}
[dateFormatter release];
}
return convertedDateString;
}
Add this to your class and use it as,
NSLog(@"%@", [self dateStringFromString:@"2nd August 2012" destinationFormat:@"dd-MM-yyyy"]);
Output: 02-08-2012
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…