0xRLA
0xRLA

Reputation: 3369

Get number of days between two NSDates when crossing new year

I need to get the number of days between two dates which I get but if I input for example: 2016-12-10 and 2017-01-10 there will be a negative number of days. This is just occur when it´s new year between those two dates.

//Get the number of days between two NSDates
func daysBetween(date: NSDate) -> Int {
    let calendar: NSCalendar = NSCalendar.currentCalendar()
    let date1 = calendar.startOfDayForDate(self)
    let date2 = calendar.startOfDayForDate(date)
    let components = calendar.components(.Day, fromDate: date1, toDate: date2, options: [])
    return components.day
}

//Using the function
let daysBetween = fromDate.daysBetween(toDate)

//Printing -334 if new year is between fromDate and toDate
print(daysBetween)

How can I modify my daysBetween(date: NSDate) function to prevent this from happening?

Edit: Please don´t pay attention to why it´s printing exacltly -334. That´s just because fromDate and toDate are different days in month. The problem a wanna solve is why the response is negative and not 31 as it should be.

Solved: It turned out to be as many of you thought. The fromDate is greater then toDate and causing a negative number. Stupid mistake. Thx guys!

Upvotes: 0

Views: 124

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

You not need to worry about the days going negative. It's better to know if the first date (for example selected from an input UIDatePicker) is bigger than another. That is handled automatically when you converted back to an NSDate. If the problem is how to print the days , you can use abs(days).

Upvotes: 1

Pushpa Y
Pushpa Y

Reputation: 1010

First compare both dates and then you can get correct positive value

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let startDate:NSDate = dateFormatter.dateFromString("2016-12-10")!
let endDate:NSDate = dateFormatter.dateFromString("2017-01-10")!

let cal = NSCalendar.currentCalendar()
let dayUnit: NSCalendarUnit = .Day
if startDate.compare(endDate) == NSComparisonResult.OrderedDescending{
   let components = cal.components(dayUnit, fromDate: endDate, toDate: startDate, options: [])
   print(components)
} else {
   let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: [])
   print(components)
}

As Describe by Leo Dabus

You can do it without comparing the dates also:

let com = cal.components(dayUnit, fromDate: startDate.earlierDate(endDate), toDate: startDate.laterDate(endDate), options: [])
print(com)

Upvotes: 0

Related Questions