将硬代码 nsstring 转换为 nsdate

convert hard code nsstring to nsdate

说我有这个 nsstring * date = @"13th May-2015" 我想把它转换成这样的@"13/05/2015"

目前我正在尝试使用 nsdateformatter 来完成它:

NSString * dateStr  = @"13th May-2015";
NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:@"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr]; 

NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init]; 
[dateFormatConverted setDateFormat:@"dd/MM/yyyy"];
NSString * convertedDateString =  [dateFormatConverted stringFromDate:date];
NSLog(@"this should be 13/05/2015,  %@", convertedDateString);

所以我希望转换后的日期字符串变成 13/05/2015。

但上面的代码无法做到这一点....任何有关代码示例的帮助都会有所帮助,谢谢大家。

2014 年 5 月 13 日不是 "dd MM-yyyy" 格式。

您必须确保您的输入字符串与格式字符串完全匹配

NSString * dateStr  = @"13th May-2015";

NSArray *stringComponentArray = [dateStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSMutableArray *workingArray = [NSMutableArray arrayWithArray:stringComponentArray];

NSMutableString *dateString = [[NSMutableString alloc]initWithString:[workingArray firstObject]];

[dateString replaceOccurrencesOfString:@"st" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:@"nd" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:@"rd" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:@"th" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];

[workingArray replaceObjectAtIndex:0 withObject:dateString];

dateStr = [workingArray componentsJoinedByString:@" "];


NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:@"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr];

NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init];
[dateFormatConverted setDateFormat:@"dd/MM/yyyy"];
NSString * convertedDateString =  [dateFormatConverted stringFromDate:date];
NSLog(@"this should be 13/05/2015,  %@", convertedDateString);

因为您的日期字符串与任何 iOS Date formatter 样式都不匹配。你需要玩 strings.Please 看看上面的解决方案。