Question

I have a Label which i want to hold a specific date. The initial date should be the current Date, and the user should be able to step through the time by the interval of a day. After a little research, I found out, that it would be best to set NSDateComponents and add them to the current Date.

My problem is as following: When I step through the time, everything seems fine, until i reach the end/beginning of a year. For instance, the date hold in the label is the 01.01.2014, when I tap the "previousDayButton" it would become 31.12.2014. I thought about asking for the date and then setting the year manually, but I can't possibly think of THAT to be the solution.

So here is my Code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupInterface];
}
- (void)setupInterface{
    orderDate = [NSDate date];
    [self updateDateLbl];
}

- (void)updateDateLbl{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd.MM.YYYY"];
    dateLbl.text = [dateFormatter stringFromDate:orderDate];    
}

- (IBAction)nextDay:(id)sender {
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    comps.day = 1;

    orderDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:orderDate options:0];
    [self updateDateLbl];
}

- (IBAction)previousDay:(id)sender {
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    comps.day = -1;
    orderDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:orderDate options:0];
    [self updateDateLbl];
}

I would love some help :)

Était-ce utile?

La solution

Use Xcode help for NSDateFormatter. From the documentation:

It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

2014 started on a Wednesday. Tuesday, 31st Dec. 2013, is in the same week - week 1 of 2014. That's what YYYY displays. yyyy displays 2013.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top