问题描述
我的应用程序中有一个DatePicker控件.例如,如果我尝试选择2011年1月1日,则返回2010年1月1日.如果选择2040年1月1日,则得出2039年1月1日,依此类推. 12月31日和1月2日为我提供了我选择的年份,所以这只是1月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?
这是代码:
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];
推荐答案
如果daycount
确实是0
,如您在评论中所说,那么这很可能是问题的根源. NSDateComponents
对象的day
属性应在日历定义的自然范围内.如果是公历,则为1-31.如果当天不在该范围内,则单位开始回绕,您可能不会得到想要的结果.
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.
这篇关于DatePicker返回错误的年份为1月1日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!