-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 回答