通过替换当前年份来转换日期字符串会产生错误的结果

时间:2013-07-04 10:36:15

标签: objective-c nsdate nsdateformatter nsdatecomponents

我的NSString值为“29/01/2010”我想将其转换为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

0 个答案:

没有答案