尝试将日期月份格式化为全名返回(null)

时间:2013-05-06 18:45:53

标签: ios objective-c nsdate nsdateformatter

我使用以下代码尝试将数字月份(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 {
...
}

2 个答案:

答案 0 :(得分: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 {

}

答案 1 :(得分: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 {
...
}