我只是得不到正确的result...so,这取决于时区,我想要的是两个日期之间的日历日期差。因此,如果一个在第一天的23:00开始,在第二天的14:00结束,它应该返回1,现在我的方法返回0,为什么?因为不到24小时?示例:
我的Nslog:
CheckForPictures departure date: Tue Jan 28 23:10:00 2020 destinationDate: Wed Jan 29 09:30:00 2020 in timeZone:Europe/Zurich and get a day difference: 0
(电脑也有苏黎世时区,所以是当地时间)
我的方法是:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:timeZone];
NSDateComponents *components = [calendar components:NSCalendarUnitDay
fromDate:self.departureTime
toDate:self.destinationTime
options:0];
NSLog(@"CheckForPictures departure date: %@ destinationDate: %@ in timeZone:%@ and get a day difference: %ld", self.departureTime, self.destinationTime, timeZone.name, components.day);
return components.day;
这段代码返回0,并且log高于log...
发布于 2020-01-25 00:23:58
我相信你问错了NSCalendar
的问题。您想知道到达日期是否与离开日期不同,但您询问的是到达和离开之间的天数。即使时间上的差异只有几分钟,也可能发生日期更改。“几分钟”四舍五入为"0天“,如果你问有多少天过去了。
您实际上想知道日期是否已更改。我想我会做一些事情,比如获取每个日期的月份日期,然后进行比较。由于没有月份有1天,我认为这是可行的。
发布于 2020-01-25 00:38:37
使用Craigs输入,我想出了这个解决方案:
- (NSInteger)calendarDaysBetweenDepartureAndArrivalTimeForTimeZone:(NSTimeZone *)timeZone
{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:timeZone];
NSDateComponents *departureComponents = [calendar components:(NSCalendarUnitDay) fromDate:self.departureTime];
NSDateComponents *destinationComponents = [calendar components:(NSCalendarUnitDay) fromDate:self.destinationTime];
NSInteger difference = destinationComponents.day - departureComponents.day;
if(difference < 0){
//Month overlapping
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.departureTime];
difference = range.length - departureComponents.day + departureComponents.day;
}
NSLog(@"CheckForPictures departure date: %@ destinationDate: %@ in timeZone:%@ and get a day difference: %ld", self.departureTime, self.destinationTime, timeZone.name, difference);
return difference;
}
https://stackoverflow.com/questions/59899752
复制相似问题