【问题标题】:About NSDateComponents:Why I can't get the correct day component?关于 NSDateComponents:为什么我无法获取正确的日期组件?
【发布时间】:2017-08-03 11:10:25
【问题描述】:

我想从 localDate 获取日期组件,[NSDate localDate] 只需将 GMT 转换为本地时间。

NSDate *localDate=[NSDate localDate];

// localDate:2017-03-13 18:35:35 +0000
NSLog(@"localDate:%@",localDate);
NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
NSLog(@"dayComponentLocal:%ld",(long)dayComponentLocal);

但为什么输出是 14?

有[NSDate localDate]的实现:

NSDate *date=[NSDate date];
NSTimeZone *zone=[NSTimeZone systemTimeZone];
NSInteger interval=[zone secondsFromGMTForDate:date];
NSDate *localDate=[date dateByAddingTimeInterval:interval];
return localDate; 

当我想获取当月的第一个工作日时还有另一个错误,代码如下:

NSDate *date=[NSDate localDate];
NSInteger dayComponents=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:date];
NSInteger secondsInADay=24*60*60;
NSDate *firstDay=[date dateByAddingTimeInterval:-((dayComponents-1)*secondsInADay)];
NSInteger weekdayComponent=[[NSCalendar currentCalendar] component:(NSCalendarUnitWeekday) fromDate:firstDay];
NSLog(@"firstDay:%@",firstDay);
NSLog(@"weekday Of firstDay:%ld",weekdayComponent);

由于错误的 dayComponents,我从 'localDate' 中再减去一天并得到错误的 firstDay '2017-02-28 20:09:32 +0000' 而不是正确的答案 '2017-03-01 20: 09:32 +0000'。 2-28 是星期二,但我得到 4,这意味着星期三, 为什么?

【问题讨论】:

    标签: ios nsdate nscalendar nsdatecomponents


    【解决方案1】:

    在取日部分之前从日期中删除时间部分。
    试试这段代码

     NSDate *localDate=[NSDate localDate];
        // localDate:2017-03-13 18:35:35 +0000
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        NSString *strDate = [dateFormatter stringFromDate: localDate];
        localDate = [dateFormatter dateFromString: strDate];
       NSInteger dayComponentLocal=[[NSCalendar currentCalendar] component:(NSCalendarUnitDay) fromDate:localDate];
       NSLog(@"dayComponentLocal:%ld",(long)dayComponentLocal);
    

    你会得到输出 13。这可能是由于时区不同

    【讨论】:

      【解决方案2】:

      您将在localDate 中添加距格林威治标准时间的秒数。由于您的时区是正数,您需要减去秒 (-interval) 才能获得 UTC。

      顺便说一下从不使用 86400 进行日期数学运算。使用NSCalendar的日期计算方法

      例如,您使用

      获取当前月份的第一个工作日
      NSCalendar *calendar = [NSCalendar currentCalendar];
      // calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
      NSDate *startDate;
      NSTimeInterval interval;
      [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:&interval forDate:[NSDate date]];
      NSInteger weekday = [calendar  component:NSCalendarUnitWeekday fromDate:startDate];
      NSLog(@"%ld", weekday);
      

      要获取与 UTC 相关的日期,请取消注释时区行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        • 2016-11-17
        • 2010-10-30
        • 1970-01-01
        • 1970-01-01
        • 2020-09-01
        相关资源
        最近更新 更多