【问题标题】:Objective-C: Get the number of calendar days between two datesObjective-C:获取两个日期之间的日历天数
【发布时间】:2020-05-10 23:25:43
【问题描述】:

我只是没有得到正确的结果......所以根据时区我想要两个日期之间的日历日差。因此,如果一个从第 1 天的 23:00 开始并在第 2 天的 14:00 结束,它应该返回 1。现在我的方法返回 0,为什么?因为不到24小时?示例:

我的日志:

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 以上记录...

【问题讨论】:

    标签: objective-c nsdate nsdatecomponents


    【解决方案1】:

    我相信您在问NSCalendar 错误的问题。您想知道到达日期是否与出发日期不同,但您要求的是到达和离开之间的 天数。即使时间差只有几分钟,日期也可能发生变化。如果您询问已经过去了多少天,“几分钟”会变成“0 天”。

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

    【讨论】:

    • 好吧,我的第一个问题:NSCalendarUnitDay 然后计算 24 小时差异?我假设是这样,我也考虑过你的解决方案。但是,假设差异不止一天和一个月重叠:我将如何计算?例如 2 月 29 日 23:00 - 3 月 2 日 01:00,在这种情况下我想要 2 的结果
    【解决方案2】:

    通过 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多