【问题标题】:Weird behavior when creating an NSDate of January the 1st and the 2nd创建 1 月 1 日和 2 日的 NSDate 时的奇怪行为
【发布时间】:2011-03-05 00:47:35
【问题描述】:

我正在创建这样的日期:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
NSInteger year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
NSLog(@"NSInteger YEAR : %d\n", year);

//minutes, hours, day and month are initialized elsewhere...

NSDateComponents *comps = [[NSDateComponents alloc] init];      
[comps setYear:year];
[comps setMonth:month];
[comps setDay:day];
[comps setHour:hours];
[comps setMinute:minutes];
NSDate *sampleDate = [gregorian dateFromComponents:comps];

NSLog(@"sampleDate YEAR : %d\n", [[dateFormatter stringFromDate:sampleDate] intValue]);

我的问题是,当日期是 1 月 1 日或 1 月 2 日时,年份不正确。这里应该是 2010 年(因为我检索今天的年份),但实际上是 2009 年......我不明白为什么 !而这只发生在这两天...

你知道为什么会这样吗? 提前谢谢你。

【问题讨论】:

    标签: iphone objective-c nsdate nscalendar nsdatecomponents


    【解决方案1】:

    请参阅Unicode standard。 “yyyy”(小写)为您提供年份,但“YYYY”(大写)为您提供日期所在周的年份(也就是说,如果日期在去年的第 52 周内,则 YYYY 将是去年)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多