tombuarts
tombuarts

Reputation: 115

DatePicker returns wrong year for Jan 1

I have a DatePicker control in my app. If I try to choose, for example, Jan 1, 2011, it returns Jan 1, 2010. If I choose Jan 1, 2040, I get Jan 1, 2039, and so on. Dec 31 and Jan 2 give me the years I select, so it is only a problem on Jan 1. I have checked my code and I don't see anywhere where I mess around with the year. Any ideas?

Here is the code:

datenow = chooseDate; 
NSDateComponents *components = [[NSDateComponents alloc] init]; 
[components setDay:(int)daycount]; 
datenow = [calendar dateByAddingComponents:components toDate:datenow options:0]; 
dateComponents = [calendar components:unitFlags fromDate:datenow]; 
year = [dateComponents year]; 
month = [dateComponents month]; 
day = [dateComponents day]; 
hour = [dateComponents hour]; 
min = [dateComponents minute];

Upvotes: 1

Views: 201

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243166

if daycount is truly 0 like you say in your comment, then that's likely the source of your problem. The day property of an NSDateComponents object should be in the natural range as defined by the calendar. In the case of the Gregorian calendar, that is 1-31. If the day is outside of that range, then units start wrapping around and you'll probably not get the result you want.

Upvotes: 3

Related Questions