I'm facing an issues and I can't seem to find a solution for it. There is a date picker and two buttons to set a start date and an end date. My app calculates the difference between these two dates.
Unfortunately, the calculated difference is not correct. For example when I set 5 Nov, 2016
as my first date and 6 Nov, 2016
as my second date, the code returns a difference of 0
days. When I change the second date to 7 Nov, 2016
it returns a difference of 1
day etc. But when I do it the other way by setting first lastDate
to 6 Nov, 2016
and then firstDate
to 5 Nov, 2016
the difference is being calculated properly (the output is 1
day). It somehow depends on which date you set first.
Here is my code:
@IBOutlet weak var startDateOutput: UILabel!
@IBOutlet weak var endDateOutput: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var answerFieldTimeDifference: UILabel!
var firstDate:NSDate?
var lastDate:NSDate?
@IBAction func startButton(sender: AnyObject)
{
firstDate = datePicker.date
let dateStr = NSDateFormatter.localizedStringFromDate(firstDate!, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
startDateOutput.text = dateStr
daysBetweenDates()
}
@IBAction func expirationButton(sender: AnyObject)
{
lastDate = datePicker.date
let dateStr = NSDateFormatter.localizedStringFromDate(lastDate!, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
endDateOutput.text = dateStr
daysBetweenDates()
}
func daysBetweenDates()
{
if var firstDate = firstDate, var lastDate = lastDate
{
let calendar = NSCalendar.currentCalendar()
let firstDate = calendar.startOfDayForDate(firstDate)
let secondDate = calendar.startOfDayForDate(lastdate)
let components = calendar.components([.Day], fromDate: date1, toDate: date2, options: [])
var differenceInDays = components.day
answerFieldTimeDifference.text = String(differenceInDays)
}
}