0

我有以下代码行将内容或标签设置为日期。

cell.birthdayLabel.text = [[GlobalBirthdaysEditor instance] getFormattedDateString:[birthday getDate]];

我需要找出年份是否等于 1604,如果是,则不显示它。

如何从该对象中提取年份,然后更改结果,使其仅打印月份和日期?

我到目前为止的代码是:

NSString *dateString = [[GlobalBirthdaysEditor instance] getFormattedDateString:[birthday getDate]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
[dateFormatter release];

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

NSInteger year = [components year];

if (year == 1604)
{
    cell.birthdayLabel.text = yearStr; //SHOULD OUTPUT JUST MONTH AND DAY
} else {
    cell.birthdayLabel.text = [[GlobalBirthdaysEditor instance] getFormattedDateString:[birthday getDate]];
}

但这不起作用。它运行,但日期始终是第二个。为什么是这样?

谢谢!

4

1 回答 1

1

您的代码有一些问题。它应该是:

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

if (year == 1604) {
    // Adjust this as needed
    NSString *yearStr = [NSString stringWithFormat:@"%d", year];
    cell.birthdayLabel.text = yearStr; //SHOULD OUTPUT JUST MONTH AND DAY
} else {
    NSString *dateString = [[GlobalBirthdaysEditor instance] getFormattedDateString:date];
    cell.birthdayLabel.text = dateString;
}

主要问题是您将新日期传递给components:方法调用,而不是传递实际日期。

没有理由在 和 之间来回NSString走动NSDate。由于您已经可以访问NSDate,请使用它。

于 2013-05-06T18:29:16.960 回答