我有以下代码行将内容或标签设置为日期。
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]];
}
但这不起作用。它运行,但日期始终是第二个。这是为什么?
谢谢!
答案 0 :(得分: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
,因此请使用它。