swift - Calculated difference of two NSDates is Wrong - fixed -
i'm facing issues , can't seem find solution it. there date picker , 2 buttons set start date , end date. app calculates difference between these 2 dates.
unfortunately, calculated difference not correct. example when set 5 nov, 2016
first date , 6 nov, 2016
second date, code returns difference of 0
days. when change second date 7 nov, 2016
returns difference of 1
day etc. but when other way setting first lastdate
6 nov, 2016
and then firstdate
5 nov, 2016
difference being calculated (the output 1
day). somehow depends on date set first.
here 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) } }
i found solution problem.
i added following 2 lines daysbetweendates() function
let firstdate = calendar.startofdayfordate(firstdate) let seconddate = calendar.startofdayfordate(lastdate)
the code above updated , should calculate difference correctly.
Comments
Post a Comment