ios - Swift days between two NSDates -
i'm wondering if there new , awesome possibility amount of days between 2 nsdates in swift / "new" cocoa?
e.g. in ruby do:
(end_date - start_date).to_i
the accepted answer won't return correct day number between 2 dates. have consider time difference well. example if compare dates 2015-01-01 10:00
, 2015-01-02 09:00
, days between dates return 0 (zero) since difference between dates less 24 hours (it's 23 hours).
if purpose exact day number between 2 dates, can work around issue this:
// assuming firstdate , seconddate defined // ... let calendar = nscalendar.currentcalendar() // replace hour (time) of both dates 00:00 let date1 = calendar.startofdayfordate(firstdate) let date2 = calendar.startofdayfordate(seconddate) let flags = nscalendarunit.day let components = calendar.components(flags, fromdate: date1, todate: date2, options: []) components.day // return number of day(s) between dates
swift 3 version
let calendar = nscalendar.current // replace hour (time) of both dates 00:00 let date1 = calendar.startofday(for: firstdate) let date2 = calendar.startofday(for: seconddate) let components = calendar.datecomponents([.day], from: date1, to: date2)
Comments
Post a Comment