【问题标题】:Get all dates (not days) between two NSDates获取两个 NSDates 之间的所有日期(不是天数)
【发布时间】:2011-09-28 04:30:23
【问题描述】:

如何获取两个日期之间的所有日期?

例如: 开始日期 = 2011/01/25 结束日期 = 2011/02/03

【问题讨论】:

  • 日期是什么意思,而不是天数?
  • @JoshCaswell 主题说“不是几天”他想要日期列表。
  • @Black Frog:但 imMobile 并没有费心说明在什么时间间隔NSTimeIntervaldouble,具有毫秒分辨率。在任何两个之间实际上有数百万个“日期”。
  • 是的,每一毫秒在“时间与空间”中都是一个不同的日期,但我相信他希望每一天都是 24 小时。

标签: objective-c nsarray nsdate


【解决方案1】:

1) 找出两个日期之间的天数。那么,

for(i=0;i<noofdays;i++)
{
//Find the next date
//add to the array
}

To find number of days

To find next date

【讨论】:

    【解决方案2】:

    NSCalendarUnit 用于定义日期之间的步骤并处理正被标准化的日期。

    iOS 8 API,Swift 2.0

        func generateDates(calendarUnit: NSCalendarUnit, startDate: NSDate, endDate: NSDate) -> [NSDate] {
    
                let calendar = NSCalendar.currentCalendar()
                let normalizedStartDate = calendar.startOfDayForDate(startDate)
                let normalizedEndDate = calendar.startOfDayForDate(endDate)
    
                var dates = [normalizedStartDate]
                var currentDate = normalizedStartDate
    
                repeat {
    
                    currentDate = calendar.dateByAddingUnit(calendarUnit, value: 1, toDate: currentDate, options: NSCalendarOptions.MatchNextTime)!
                    dates.append(currentDate)
    
                } while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
    
                return dates
        }
    

    【讨论】:

    • 谢谢。我正在使用它的 Objective-c 版本来完成我的场景。
    【解决方案3】:

    要查找两个 NSD 日期之间的所有天数:

    - (void)cerateDaysArray{
        _daysArray = [NSMutableArray new];
        NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
        [calendar setTimeZone:[NSTimeZone systemTimeZone]];
        NSDate *startDate = [_minDate copy];
        NSDateComponents *deltaDays = [NSDateComponents new];
        [deltaDays setDay:1];
        [_daysArray addObject:startDate];
        while ([startDate compare:_maxDate] == NSOrderedAscending) {
           startDate = [calendar dateByAddingComponents:deltaDays toDate:startDate options:0];
           [_daysArray addObject:startDate];
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2013-08-09
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      相关资源
      最近更新 更多