gpt4 book ai didi

iPhone NSDateComponent 日期错误 1.1.2011?

转载 作者:行者123 更新时间:2023-12-03 19:31:37 26 4
gpt4 key购买 nike

我用“DateFromComponents”设置了一个日期,当我读出它时......它是错误的。我必须将日期设置为第二天或以后的任何时间,这样我才能得到正确的年份?!?我设置了 2011 年,当我读出它时,我得到了 2010 年!!

<小时/>
 day = 1;
month = 1;
year = 2011;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
NSDate *date = [gregorian dateFromComponents:components];
[gregorian release];


NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"DD MMMM YYYY"];
NSLog (@"hmm: %@",[dateFormatter stringFromDate:actDate]);

-------- 这里我得到1 一月 2010///2010 而不是 2011 !?!?

如何解决这个问题。

谢谢克里斯

最佳答案

我运行了这段代码:

NSInteger day = 1;
NSInteger month = 1;
NSInteger year =0;
NSCalendar *gregorian;
NSDateComponents *components;
NSDate *theDate;
NSDateFormatter *dateFormatter;
for (int i=2005; i<2015; i++) {
year= i;
gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
theDate = [gregorian dateFromComponents:components];
[gregorian release];


dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"DD MMMM YYYY"];
NSLog(@"year=%d",year);
NSLog (@"hmm: %@",[dateFormatter stringFromDate:theDate]);
NSLog(@"theDate=%@\n\n",theDate);
}

...并得到以下输出:

 year=2005
hmm: 01 January 2004
theDate=2005-01-01 00:00:00 -0600

year=2006
hmm: 01 January 2006
theDate=2006-01-01 00:00:00 -0600

year=2007
hmm: 01 January 2007
theDate=2007-01-01 00:00:00 -0600

year=2008
hmm: 01 January 2008
theDate=2008-01-01 00:00:00 -0600

year=2009
hmm: 01 January 2008
theDate=2009-01-01 00:00:00 -0600

year=2010
hmm: 01 January 2009
theDate=2010-01-01 00:00:00 -0600

year=2011
hmm: 01 January 2010
theDate=2011-01-01 00:00:00 -0600

year=2012
hmm: 01 January 2012
theDate=2012-01-01 00:00:00 -0600

year=2013
hmm: 01 January 2013
theDate=2013-01-01 00:00:00 -0600

year=2014
hmm: 01 January 2014
theDate=2014-01-01 00:00:00 -0600

显然问题出在格式化程序而不是日期。但是,我不知道格式化程序有什么问题。 。

编辑:

转移:

[dateFormatter setDateFormat:@"DD MMMM YYYY"];

...至:

[dateFormatter setDateFormat:@"DD MMMM yyyy"];

...解决了问题,尽管我不知道为什么。

关于iPhone NSDateComponent 日期错误 1.1.2011?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3220176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com