-2

次のコードを使用して、数字の月 (5) を完全な名前 (May) に変換しようとしています。ただし、設定を MM から MMMM に変更すると、null が返されます。どうしてこれなの?

NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger year = [components year];

if (year == 1604) {
    NSString *monthNumberString = [NSString stringWithFormat:@"%d", [components month]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM"];
    NSDate *date = [formatter dateFromString:monthNumberString];
    NSString *stringFromDate = [formatter stringFromDate:date];
    NSString *monthDay = [NSString stringWithFormat:@"%@, %d", stringFromDate, [components day]];
    cell.birthdayLabel.text = monthDay;
} else {
...
}
4

2 に答える 2

1

試す

NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
                                                               fromDate:date];
NSInteger year = [components year];

if (year == 1604)
{
    NSString *monthNumberString = [NSString stringWithFormat:@"%d", [components month]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM"];
    NSDate *date = [formatter dateFromString:monthNumberString];
    [formatter setDateFormat:@"MMMM"];
    NSString *stringFromDate = [formatter stringFromDate:date];
    NSString *monthDay = [NSString stringWithFormat:@"%@, %d", stringFromDate, [components day]];

    NSLog(@"%@",monthDay);

    cell.birthdayLabel.text = monthDay;
}
else {

}
于 2013-05-06T18:59:09.197 に答える
1

あなたはすでに日付を持っています。フォーマットするだけです:

NSDate *date = [birthday getDate];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger year = [components year];

if (year == 1604) {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM, d"];
    NSString *stringFromDate = [formatter stringFromDate:date];
    cell.birthdayLabel.text = stringFromDate;
} else {
...
}
于 2013-05-06T19:05:07.623 に答える