我有一个代码片段,它会占用一个日期并尝试将其转换为没有时间组件的日期。然后我使用这个修剪过的数据来保存/从核心数据中取出。
-(NSDate*)dateWithNoTimeComponents:(NSDate*)startDate
{
//
NSCalendar *calendar = [NSCalendar currentCalendar];
NSNumber* count = 0;
int secondsPerDay = 86400;
//break the date and create fractional components for that date
NSDateComponents *components = [calendar components:(NSWeekdayCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:startDate];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
//update daily count
//remove fractional componets from the date, effectively creating a key per day
return [NSDate dateWithTimeInterval:-((hour*60+minute)*60+second) sinceDate:startDate];
}
我担心的是,这可能不适用于来自不同时区的日期。将不同时间戳的日期设置会影响此方法吗?例如,如果我在GMT -5时区,然后进入GMT -8时区,此方法产生的修剪日期是否仍然正确? 我是否需要在此计算中的某处包含时区偏移/夏令时以使其全局正确?
答案 0 :(得分:2)
最好的办法是遵循在GMT中执行所有操作的SDK约定,只转换为本地时区以供用户查看。
您的代码会在小时和分钟上进行数学计算,从而为边缘情况留下错误的机会。最好让sdk做数学运算。要获得给定日期的零小时,请尝试这样的事情......
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:startDate];
NSDate *justTheDay = [calendar dateFromComponents:components];
答案 1 :(得分:0)
我以前也使用与danh相同的解决方案,但耗时太多(约 1642.0ms Instruments中的CPU时间''Time Profiler')。它使用它几次减慢了我的整个应用程序。
最后我找到 this answer 并在我的最终方法中使用它:
// this method takes around 100ms CPU-time (measured with instruments)
- (NSDate*) truncateDate : (NSDate*) date
toCalendarUnit : (NSCalendarUnit) calendarUnit
{
NSDate *truncatedDate;
[[NSCalendar currentCalendar] rangeOfUnit : calendarUnit
startDate : &truncatedDate
interval : NULL
forDate : date];
return truncatedDate;
}
此方法只需 100.0ms CPU-Time。
对我来说,这是一个更好的解决方案。