NSDateComponents转换时间的坑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18683985/article/details/84565597

这个坑是最近做一个日历的时候碰到的.
后台给定的时间范围是1970年起的时间戳.(开始月的时间戳,结束月的时间戳).当时我就想当然的用NSDate与NSDateFormatter来做了.反正往后切一个月就是时间戳加上60 * 60 * 24.也简单.

就当我切换月的时候我想到了.自己使用dateFormatter还需要截取区域来判断年月是否相等.那我为何不直接使用NSCalendar里头的NSDateComponents来直接计算呢.

- (NSDateComponents *)dateComponents {
    if (!_dateComponents) {
        _dateComponents = [[NSDateComponents alloc] init];
    }
    return _dateComponents;
}

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSCalendarUnit calendarUnit = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday;
    self.dateComponents = [calendar components:calendarUnit fromDate:[NSDate date]];

对于这个类来说,有着下面有些诱人的属性

@property NSInteger era;
@property NSInteger year;
@property NSInteger month;
@property NSInteger day;
@property NSInteger hour;
@property NSInteger minute;
@property NSInteger second;
@property NSInteger nanosecond API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
@property NSInteger weekday;
@property NSInteger weekdayOrdinal;
@property NSInteger quarter API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
@property NSInteger weekOfMonth API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
@property NSInteger weekOfYear API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
@property NSInteger yearForWeekOfYear API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));

随后我想当然的想到.我为啥不获取第一个时间戳之后直接让day += 1呢…然后我就陷入了一个死循环了(判断年月日相等不会 == YES)…当时我的心里活动就是(卧槽.怎么初始化个年月这么慢,苹果垃圾…)…过了一会儿.承载日历的数组终于由于往里面塞入的对象过多而宣告崩溃…当时的代码我也木有了…我可以复现一下给你们看看…

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.dateComponents setDay:self.dateComponents.day + 1];
    NSLog(@"%.4ld年%.2ld月%.2ld日",self.dateComponents.year ,self.dateComponents.month ,self.dateComponents.day);
}

到这里还是比较正常的…那么,我们看看打印是什么情况
在这里插入图片描述

这…11月份哪里来的31日…31日就算了…35日是什么鬼…
好吧.只能老老实实的给时间戳给NSDateComponents计算了.
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_18683985/article/details/84565597