我有值为“29/01/2010”的 NSString,我想将其转换为 NSDate,并将年份值替换为当前年份。
为此,我尝试过
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2013];
[components setMonth:01];
[components setDay:29];
NSLog(@"%@",[calendar dateFromComponents:components]);
它给出的结果是2013-01-28 18:30:00 +0000
另一种尝试的方法是
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSString *yearString = [formatter stringFromDate:[NSDate date]];
NSArray *dateComponents = [aStrBirthDate componentsSeparatedByString:@"/"];
aStrBirthDate = [aStrBirthDate stringByReplacingOccurrencesOfString:[dateComponents lastObject] withString:yearString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:aStrBirthDate];
这也给出了相同的结果2013-01-28 18:30:00 +0000