3

「DateFromComponents」で日付を設定し、それを読み取ると...間違っています。正しい年を取得するには、DAYを2日以降に設定する必要がありますか?!?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 January 2010 /// 2010 not 2011!?!?

それを修正する方法。

thx chris

4

2 に答える 2

6

私はこのコードを実行しました:

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"];

...理由はわかりませんが、問題は解決します。

于 2010-07-10T18:32:29.153 に答える
4

http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patternsに記載されているように、YYYYは暦年とは異なる場合があります。

1月1日は、前年の最後の週に属することができます。YYYYは、年の週(つまり、2009年の第52週)に言及するときに使用された年を表示します。2010年1月1日が2009年の第52週に属する場合、YYYYは2009を表示します。

そのため、yyyyを使用する必要があります。

于 2010-07-11T09:06:39.227 に答える