0

値が「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

4

0 に答える 0