5

I am having two dates star date and last date for a entry in database(core data).Now i need to create a list of dates in an array form. Start date and end date having string form in data base.

format of date is MM/dd/yyyy.

Ishu
  • 12,797
  • 5
  • 35
  • 51
  • Duplicate: http://stackoverflow.com/questions/4544406/find-exact-difference-between-two-dates – pheelicks Feb 04 '11 at 08:38
  • 1
    @pheelicks read carefully the question,you send a link of question in which difference between two date is desired.and i am having answer on this question also. – Ishu Feb 04 '11 at 08:40
  • @pheelicks I don't think that this question is the same as the one that you are pointing out as a duplicate. – xyzzycoder Feb 04 '11 at 08:46

6 Answers6

11
// minDate and maxDate represent your date range
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSInteger dayCount = 0;
while ( TRUE ) {
    [days setDay: ++dayCount];
    NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: minDate options: 0];
    if ( [date compare: maxDate] == NSOrderedDescending )
        break;
    // Do something with date like add it to an array, etc.
}
[days release];
[gregorianCalendar release];
Costique
  • 23,712
  • 4
  • 76
  • 79
  • You're welcome. NSCalendar API looks a bit verbose, but it is *the* correct way to perform calendric calculations. – Costique Feb 04 '11 at 11:54
4

I have a more general approach with NSCalendarUnit for defining the step between the dates & taking care of the dates being normalized.

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
    }
Kex
  • 776
  • 10
  • 22
  • @G.Abhisek I take the 2 dates as input parameters & normalize them to start at the start of their day. Afterwards I iterate by a step defined as the calendar unit which is the input parameter until I reach the 2nd date. – Kex Aug 05 '16 at 01:23
  • In Swift 3: `calendar.date(byAdding: calendarUnit, value: 1, to: currentDate)!` – Timur Bernikovich Jun 13 '17 at 12:36
1

Here is Costique's solution in swift but with a little swift flash.

func ...(lhs:NSDate, rhs:NSDate) -> [NSDate] {
  var dates: [NSDate] = []
  var cal = NSCalendar.currentCalendar() // or NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
  var days = NSDateComponents()
  var dayCount = 0
  while true {
    days.day = dayCount
    let date:NSDate = cal.dateByAddingComponents(days, toDate: lhs, options: NSCalendarOptions.allZeros)!
    if date.compare(rhs) == .OrderedDescending {
      break
    }
    dayCount += 1
    dates.append(date)
  }

  return dates
}

let fromDate = NSDate(timeIntervalSince1970: 1440711319)
let toDate = NSDate(timeIntervalSince1970: 1441316129)

fromDate...toDate // => ["Aug 27, 2015, 2:19 PM", "Aug 28, 2015, 2:19 PM", "Aug 29, 2015, 2:19 PM", "Aug 30, 2015, 2:19 PM", "Aug 31, 2015, 2:19 PM", "Sep 1, 2015, 2:19 PM", "Sep 2, 2015, 2:19 PM", "Sep 3, 2015, 2:19 PM"]
Nick Wargnier
  • 1,461
  • 14
  • 8
1

You could accomplish this pretty easily by converting the start date to a Julian day (which will produce a float value), iterating through to the end date, and converting the iterated values from Julian days back into NSDate objects.

I posted some methods in my answer to this question (below) that will provide the necessary conversions.

How get a datetime column in SQLite with Objective C

Community
  • 1
  • 1
xyzzycoder
  • 1,831
  • 13
  • 19
0

Swift 3.0:

Suppose you want get the array of dates from today upto next 60 days.

extension Date {
    func generateDates(startDate :Date?, addbyUnit:Calendar.Component, value : Int) -> [Date]
{
    let calendar = Calendar.current
    var datesArray: [Date] =  [Date] ()

    for i in 0 ... value {
        if let newDate = calendar.date(byAdding: addbyUnit, value: i + 1, to: startDate!) {
            datesArray.append(newDate)
        }
    }

    return datesArray
}
}

Usage:

var datesArrayByAddingDays:[Date]?

override func viewWillAppear(_ animated: Bool) {

    datesArrayByAddingDays = Date().generateDates(startDate: Date(), addbyUnit: .day, value: 60)
}
Alvin George
  • 14,148
  • 92
  • 64
0

Swift4 version of @Nick Wargnier's:

func ...(lhs:Date, rhs:Date) -> [Date] {
    var dates = [Date]()
    let cal = NSCalendar.current
    var days = DateComponents()
    var dayCount = 0
    while true {
        days.day = dayCount
        let date = cal.date(byAdding: days, to: lhs)!
        if date.compare(rhs) == .orderedDescending {
            break
        }
        dayCount += 1
        dates.append(date)
    }

    return dates
}
Chris Prince
  • 7,288
  • 2
  • 48
  • 66