Objective-C:获取两个日期之间的日历天数

时间:2020-01-24 15:50:38

标签: objective-c nsdate nsdatecomponents

我只是没有得到正确的结果...所以根据时区,我希望两个日期之间的日历日差。因此,如果一个从第1天的23:00开始到第2天的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并在日志上方记录...

2 个答案:

答案 0 :(得分:0)

我相信您是在问NSCalendar一个错误的问题。您想知道到达日期是否与出发日期不同,但是您要询问到达和离开之间的天数。即使时间差只有几分钟,也可能发生日期更改。如果询问已过去多少天,则“几分钟”将舍入为“ 0天”。

您实际上想知道日期是否已更改。我想我会做一些事情,例如获取每个日期的月份并进行比较。由于没有月份有1天的时间,所以我认为这会起作用。

答案 1 :(得分:0)

借助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;
}