UIDatePicker adding one to year

2020-04-17 08:00发布

I have a very strange and confusing problem. I can't find anything about it and it seems like a bug with Apple, but if anyone has a suggestion on how to get around this it would be helpful. There are certain dates that are adding 1 to the year with a UIDatePicker, seems to never be less than December 27th. I've went back a few years to try and find a pattern. Here are some examples:

Any date picked >= December 28th in 2014 changes to 2015
>= 29th in 2013 -> 2014
>= 30th in 2012 -> 2013
2011 (issue doesn't occur)
>= 26th in 2010 -> 2011
>= 27th in 2009 -> 2010
>= 28th in 2008 -> 2009
>= 30th in 2007 -> 2008
=  31st in 2006 -> 2007
2005  (issue doesn't occur)
>= 26th in 2004 -> 2005
>= 28th in 2003 -> 2004
>= 29th in 2002 -> 2003
>= 30th in 2001 -> 2002
=  31st in 2000 -> 2001
=  31st in 1999 -> 2000
>= 27th in 1998 -> 1999
>= 28th in 1997 -> 1998
>= 29th in 1996 -> 1997
=  31st in 1995 -> 1996
1994  (issue doesn't occur)

Hopefully that's not too confusing. I can't seem to find a definitive pattern and can't figure out how to get around this issue. Here is the code I'm using to retrieve the date from the picker:

NSString *date;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
date = [formatter stringFromDate:datePicker.date];

Any help on this would be greatly appreciated.

2条回答
成全新的幸福
2楼-- · 2020-04-17 08:35

In NSDateFormatter, "Y" and "y" specify different kinds of year that may start on different days. You want "y".

From the NSDateFormatter documentation:

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.

查看更多
够拽才男人
3楼-- · 2020-04-17 08:45

I don´t know if it would change anything but you could try

[formatter setDateFormat:@"yyyy:MM:dd"];

查看更多
登录 后发表回答