【问题标题】:NSDateComponents giving wrong day for 28 FebNSDateComponents 在 2 月 28 日给出错误的日期
【发布时间】:2011-04-01 22:27:56
【问题描述】:

我正在尝试在 2 月内进行搜索。所以我想弄清楚最后一天是28还是29。我正在从3月底做减法

NSDate* endFeb = [march dateByAddingTimeInterval: (NSTimeInterval) -24 * 3600];
NSDateComponents *feb = [gregorian components: units fromDate: endFeb];

这给了我正确的日期,但不是正确的日期

(gdb) po [gregorian dateFromComponents: feb]
2011-02-28 00:00:00 +0000
(gdb) p (int) [feb day]
$1 = 27

如果重要的话,这在 iPad 4.3 模拟器上。

【问题讨论】:

    标签: iphone nsdate nsdatecomponents


    【解决方案1】:

    要确定 2 月是 28 天还是 29 天,您可以使用以下代码:

    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:2008];
    [components setMonth:2];
    [components setDay:1];
    NSDate *febDate = [calendar dateFromComponents:components];
    
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:febDate];
    
    NSLog(@"%u days in february", range.length);
    

    这样您就不必弄乱时区偏移量。我想这是你的代码的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多