【问题标题】:Get Wrong NSDate out of NSDateComponent with 2011-01-01使用 2011-01-01 从 NSDateComponent 中获取错误的 NSDate
【发布时间】:2011-03-09 05:23:30
【问题描述】:

我从 NSDateComponents 和 NSDateFormatter 得到了一些奇怪的结果。

我有以下方法将给定日期的时间设置为上午 10 点

+ (NSDate *)getTenOClockOnDate:(NSDate*)inputDate
{

NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];

NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit ) fromDate:inputDate];

[components setHour:10];
[components setMinute:0];
[components setSecond:0];

// construct new date and return
NSDate *newDate = [cal dateFromComponents:components];

NSLog(@"input date: %@ -- new date: %@", inputDate, newDate);

return newDate;
}

当我拨打以下电话时:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];    
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2010-12-31"]];
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-01"]];
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-02"]];

只有第二行,我得到了意想不到的结果:

input date: 2010-12-31 05:00:00 GMT -- new date: 2010-12-31 15:00:00 GMT
input date: 2011-01-01 05:00:00 GMT -- new date: 2011-12-31 15:00:00 GMT
input date: 2011-01-02 05:00:00 GMT -- new date: 2011-01-02 15:00:00 GMT

问题出在第二条记录上,2011-01-01,只需将小时设置为 10,它就变成了 2011-12-31。

【问题讨论】:

    标签: iphone objective-c nsdate nsdateformatter nsdatecomponents


    【解决方案1】:

    Println(date) 在 Swift 中不正确,使用 nsdateformatterstringfromdate

    我猜这也适用于 nslog,在 Objective-C 中

    【讨论】:

      【解决方案2】:

      这确实看起来很奇怪...虽然您的代码看起来应该没问题,但我的预感是当您初始化 NSDateComponents 对象时,您没有启用 NSHourCalendarUnit 和 @ 987654323@。

      虽然您认为这没有必要,但我认为我遇到了类似的问题,发现需要打开这些才能正确修改日期时间并获得您想要的结果。

      如果这不起作用,也许尝试设置日历的时区可能是必要的,因为它们是我所做的唯一不同之处,而且看起来确实很有魅力。

      【讨论】:

      • 啊哈,好发现!我也忽略了那个。
      【解决方案3】:

      这将从 NSDateComponents 中获得正确的 NSDate 值,

      NSDateFormatter* df = [[NSDateFormatter alloc]init];
      [df setDateFormat:@"yyyy-MM-dd"];
      NSDate* date = [df dateFromString:@"2011-01-01"];
      NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
      NSInteger day = [components day];    
      NSInteger month = [components month];
      NSInteger year = [components year];
      [df release];
      
      NSLog(@"Day : %d, Month : %d, Year : %d",day,month,year);
      

      它会帮助你。

      【讨论】:

        猜你喜欢
        • 2011-05-24
        • 1970-01-01
        • 2018-07-09
        • 2011-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        • 2020-05-12
        相关资源
        最近更新 更多