swift - How can I figure out the day difference in the following example -
i calculating day difference between 2 dates, figured out the following code giving me difference 24 hours rather difference in date. have following code:
func daysbetweendate(startdate: nsdate, enddate: nsdate) -> int { let calendar = nscalendar.currentcalendar() let components = calendar.components([.day], fromdate:startdate, todate: enddate, options: []) return components.day }
so, following example result:
lastlaunch:2016-06-10 01:39:07 +0000
toady: 2016-06-11 00:41:41 +0000
daydiff:0
i have expected day difference one, since last launch on 10th , today 11th. how can change code give me actual difference in date days?
you can use calendar method date bysettinghour noon time startdate , enddate, make calendar calculations not time sensitive:
xcode 8.2.1 • swift 3.0.2
extension date { var noon: date? { return calendar.autoupdatingcurrent.date(bysettinghour: 12, minute: 0, second: 0, of: self) } func daysbetween(_ date: date) -> int? { guard let noon = noon, let date = date.noon else { return nil } return calendar.autoupdatingcurrent.datecomponents([.day], from: noon, to: date).day } } let startdatestring = "2016-06-10 01:39:07 +0000" let todaystring = "2016-06-11 00:41:41 +0000" let formatter = dateformatter() formatter.calendar = calendar(identifier: .iso8601) formatter.locale = locale(identifier: "ex_us_posix") formatter.dateformat = "yyyy-mm-dd hh:mm:ss xxxx" if let startdate = formatter.date(from: startdatestring), let enddate = formatter.date(from: todaystring), let days = startdate.daysbetween(enddate) { print(startdate) // "2016-06-10 01:39:07 +0000\n" print(enddate) // "2016-06-11 00:41:41 +0000\n" print(days ?? "nil") // 1 }
swift 2.x
extension nsdate { var noon: nsdate { return nscalendar.currentcalendar().datebysettinghour(12, minute: 0, second: 0, ofdate: self, options: [])! } } func daysbetweendate(startdate: nsdate, enddate: nsdate) -> int { return nscalendar.currentcalendar().components([.day], fromdate: startdate.noon, todate: enddate.noon, options: []).day }
Comments
Post a Comment