[英]Objective-c how to get a date with no time components at GMT timezone?
我得到了一個帶日期的代碼片段,並嘗試將其轉換為沒有時間成分的日期。 然后,我使用這些修整后的數據進行核心數據的保存/獲取。
-(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];
}
我擔心的是,這可能不適用於來自不同時區的日期。 將來自不同時間戳的日期放入會影響此方法嗎? 例如,如果我處於格林尼治標准時間-5時區,然后移至格林尼治標准時間-8時區,用此方法產生的修正日期仍然正確嗎? 我是否需要在此計算中將時區偏移量/夏時制包括在內才能使其在全球范圍內正確?
最好的做法是遵循SDK約定,在GMT中進行所有操作,僅轉換為本地時區以供用戶查看。
您的代碼以小時和分鍾為單位進行數學運算,從而為邊緣情況下出現錯誤提供了機會。 最好讓SDK進行數學運算。 要獲得給定日期的零時,請嘗試以下操作...
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:startDate];
NSDate *justTheDay = [calendar dateFromComponents:components];
我也曾經采用與danh相同的解決方案,但是它太耗時 (在Instruments'Time Profiler'中,CPU-Time約為1642.0ms )。 數次使我的整個應用程序運行變慢。
最后,我找到了這個答案 ,並在我的最終方法中使用了它:
// 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.0毫秒的 CPU時間。
對我來說,這是一個更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.