我正在尝试使用NSDateComponents来测试动态日期是否“今天” . 我用它来提取年/月/日,然后比较两个NSDates的值 . 理论上这应该有效 . 我在东海岸,所以EST,-5来自UTC .
实际当前时间:美国东部时间12:40:53
以下是UTC中正确的NSDates . 时间是正确的UTC:
-
当前[NSDate date]:2016-01-19 17:40:53 0000
-
活动NSDate:2016-01-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
}
1 回答
您正在更改
NSDateComponents
的时区 . 但是你想在调用components
(或调用NSCalendar
天检查例程)之前更改日历的时区,例如:但是,如果当地时间是
2016-01-19 21:00:00 -0500
(即20日,UTC) . 您是否希望它表示它与您示例中的活动日期同一天?如果是这样,那么你真的说你想使用_date
的本地日历和activityModel.date
的UTC,例如: