我试图使用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