最近一个公司一个项目里有个坑,显示不了0点的数据,修改起始时间为前一天23点59分59秒则可以显示。
查看了获取当天0点代码,和网上查到的结果基本一致,如下所示(使用Category On NSDate):
1 - (NSDate *)zeroOfDate 2 { 3 NSCalendar *calendar = [NSCalendar currentCalendar]; 4 NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:self]; 5 components.hour = 0; 6 components.minute = 0; 7 components.second = 0; 8 return [calendar dateFromComponents:components]; 9 }
加上Log发现return的date NSTimeInterval的小数点后的值不为0,因为nanosecond不为0,而iOS里又不能使用components.nanosecond = 0,于是用以下办法解决:
1 - (NSDate *)zeroOfDate 2 { 3 NSCalendar *calendar = [NSCalendar currentCalendar]; 4 NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:self]; 5 components.hour = 0; 6 components.minute = 0; 7 components.second = 0; 8 9 // components.nanosecond = 0 not available in iOS 10 NSTimeInterval ts = (double)(int)[[calendar dateFromComponents:components] timeIntervalSince1970]; 11 return [NSDate dateWithTimeIntervalSince1970:ts]; 12 }
做个标记,以防以后被坑。