Skip to content

Instantly share code, notes, and snippets.

@ishaq
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishaq/e5bbeb0595123d3ca0e7 to your computer and use it in GitHub Desktop.
Save ishaq/e5bbeb0595123d3ca0e7 to your computer and use it in GitHub Desktop.
class func daysToNextBirthday(birthdate: NSDate?) -> Int {
if (birthdate != nil) {
}
else {
return Int.max
}
let calender = NSCalendar.currentCalendar()
let now = NSDate()
let nowComponents = calender.components(NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.YearCalendarUnit, fromDate: now)
let birthdayComponents = calender.components(NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.YearCalendarUnit, fromDate: birthdate!)
// birthday is today or later this year
if(birthdayComponents.month > nowComponents.month || (birthdayComponents.month == nowComponents.month && birthdayComponents.day >= nowComponents.day)) {
birthdayComponents.year = nowComponents.year
}
else { // birthday passed, next birthday would be next year
birthdayComponents.year = nowComponents.year + 1
}
let daysRemaining = calender.components(NSCalendarUnit.DayCalendarUnit, fromDateComponents: nowComponents, toDateComponents: birthdayComponents, options: nil)
let nextBirthday = calender.dateFromComponents(birthdayComponents)
println("birthdate: \(birthdate!) - nextBirthday: \(nextBirthday) - daysRemaining: \(daysRemaining.day)")
return daysRemaining.day
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment