我試圖使用NSDateComponents來測試動態日期是否發生「今天」。我用它來提取年/月/日,然後比較兩個NSDates的值。理論上這應該起作用。我在東海岸,所以從UTC UTC-5。NSDateComponents將UTC日期轉換爲本地時區,搞亂了「今天」nsdate比較
當前時刻:12時四十分53秒,EST
這裏是正確的NSDates,在UTC。時代在正確的UTC:
- 電流[NSDate的日期]:2016年1月19日十七點40分53秒+0000
- 活動的NSDate:2016年1月19日00:00:00 +0000
這是我的日誌,顯示每個日期。它將日期轉換爲當地時區2016-01-19 07:00:00。由於當前日期處於當天的中間位置,因此-5小時的偏移量不會導致它轉換幾天。然而,午夜人卻轉移到了一天。我怎樣才能得到它尊重UTC?
的NSLog:
2016-1-19 12:40:53 (America/New_York (EST) offset -18000),
2016-1-18 19:0:0 (America/New_York (EST) offset -18000)
代碼:
NSDateComponents *current = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond |NSCalendarUnitTimeZone fromDate:_date];
NSDateComponents *activity = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond |NSCalendarUnitTimeZone fromDate:activityModel.date];
// attempt to set timezones to UTC manually, doesn't change anything
activity.calendar = [NSCalendar currentCalendar];
activity.calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
current.calendar = [NSCalendar currentCalendar];
current.calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSLog(@"%ld-%ld-%ld %ld:%ld:%ld (%@), %ld-%ld-%ld %ld:%ld:%ld (%@)", (long)[current year],(long)[current month], (long)[current day], (long)[current hour], (long)[current minute], (long)[current second], [current timeZone].description, (long)[activity year], (long)[activity month], (long)[activity day],(long)[activity hour], (long)[activity minute], (long)[activity second],[current timeZone].description);
if([current day] == [activity day] &&
[current month] == [activity month] &&
[current year] == [activity year] &&
[current era] == [activity era]) {
// do something if activity on current day
}
你可以只問NSCalendar這個問題。可能比調試日期代碼更容易。請參閱' - [NSCalendar isDateInToday]'。 – Avi
試過這個: 如果([[NSCalendar currentCalendar]但的確更簡單一些。 – Miro