ios - Swift Problems understanding the result of Calendar.dateComponents -
in app have list of contacts including contacts birthday. want see of contacts have birthday within in next 7 days. using filter on list filter , return thos contacts match
let timespan = 7 let cal = calendar.current let = date() var birthdays = contactlist.filter { (contact) -> bool in if let birthdate = contact.birthdate { let difference = cal.datecomponents([.day,.year], from: birthdate date, to: now! ) print("bd:\(birthdate) : diff \(difference.day!)") return ((difference.day! <= timespan) && difference.day! >= 0) } return false }
my hope so. result weired. added ugly print closure in order see result of 'difference'
what odd instance following: today 2017-08-18 1 of contacts born on 1987-08-19. instead of returning difference.day of 1 receive 364. if swap from: , to: in datecomponents receive difference.day of -364.
my expectation have difference.day = 1.
again in playground
import uikit var = date() let dateformatter = dateformatter() dateformatter.dateformat = "yyyy-mm-dd" let s = dateformatter.date(from: "1987-08-19") let cal = calendar.current let difference = cal.datecomponents([calendar.component.day,calendar.component.month,calendar.component.year], from: s!, to: ) print("\(difference.day!)") // result difference.day = 30
what doing wrong?
thanks
you can create extension return number of days next birthday follow:
extension date { var year: int { return calendar.current.component(.year, from: self) } var month: int { return calendar.current.component(.month, from: self) } var day: int { return calendar.current.component(.day, from: self) } var noon: date { return calendar.current.date(bysettinghour: 12, minute: 0, second: 0, of: self)! } var daysfrombirthday: int { let nextbirthdate = datecomponents(calendar: .current, year: date().year + (month < date().month ? 1 : 0), month: month, day: day, hour: 12).date ?? date.distantfuture return calendar.current.datecomponents([.day], from: date().noon, to: nextbirthdate).day ?? 0 } }
and can filter objects follow:
let timespan = 0...7 let birthdays = contactlist.filter { timespan ~= $0.birthdate?.daysfrombirthday ?? -1 }
Comments
Post a Comment