0

I have the following line of code which sets the content or a label to a date.

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

I need to find out in the year is equal to 1604 and, if so, not show it.

How can I pull the year from this object and then alter the result so it just prints month and day?

The code I have so far is:

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]];
}

But this does not work. It runs, but the date is always the second one. Why is this?

Thank you!

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 に答える