我正在构建生日提醒应用。我希望用户能够看到有多少天,直到有人的下一个生日。
我们说我有NSDate()
= 2015-06-30 07:21:47 +0000
生日的NSDate
= 1985-08-29 12:00:00 +0000
我如何获得下一个生日的天数?我使用了this之类的东西,它给出了自日期实际开始以来的负天数(在出生日期中有数千天)。然后,我将添加365数字差异,直到它是积极的,但它仍然返回一个不稳定的数字。我假设是因为闰年或其他事情。
我能实施一种方法吗?以某种方式平衡年份组成部分,以便它始终比较下一个生日而不是原始生日?
编辑:
这是我正在使用的功能:
func daysBetween(date1: NSDate, date2: NSDate) -> Int {
var calendar: NSCalendar = NSCalendar.currentCalendar()
let date1 = calendar.startOfDayForDate(date1)
let date2 = calendar.startOfDayForDate(date2)
let flags = NSCalendarUnit.CalendarUnitDay
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: nil)
return components.day
}
根据我发布的示例日期,我会像这样使用它:
// sampleDate = 1985-08-29 12:00:00 +0000
daysBetween(sampleDate, date2: NSDate())
// --> 10897
无论是正面还是负面,这个数字都是数千。我希望将其平衡到下一个日历生日的天数。
答案 0 :(得分:8)
您需要的是计算(日和月)的下一次出现 今天过后生日的一部分:
let cal = NSCalendar.currentCalendar()
let today = cal.startOfDayForDate(NSDate())
let dayAndMonth = cal.components(.CalendarUnitDay | .CalendarUnitMonth,
fromDate: birthday)
let nextBirthDay = cal.nextDateAfterDate(today,
matchingComponents: dayAndMonth,
options: .MatchNextTimePreservingSmallerUnits)!
说明:
MatchNextTimePreservingSmallerUnits
选项的目的是
如果生日是在2月29日(在公历中),它的下一次出现将是
如果年份不是闰年,则计算为3月1日。
您可能需要先检查生日是今天,看起来如此
在这种情况下,nextDateAfterDate()
将返回下一个生日。
然后您可以像往常一样计算天数差异:
let diff = cal.components(.CalendarUnitDay,
fromDate: today,
toDate: nextBirthDay,
options: nil)
println(diff.day)
更新Swift 2.2(Xcode 7.3):
let cal = NSCalendar.currentCalendar()
let today = cal.startOfDayForDate(NSDate())
let dayAndMonth = cal.components([.Day, .Month],
fromDate: birthday)
let nextBirthDay = cal.nextDateAfterDate(today,
matchingComponents: dayAndMonth,
options: .MatchNextTimePreservingSmallerUnits)!
let diff = cal.components(.Day,
fromDate: today,
toDate: nextBirthDay,
options: [])
print(diff.day)
更新Swift 3(Xcode 8 GM):
let cal = Calendar.current
let today = cal.startOfDay(for: Date())
let dayAndMonth = cal.dateComponents([.day, .month], from: birthday)
let nextBirthDay = cal.nextDate(after: today, matching: dayAndMonth,
matchingPolicy: .nextTimePreservingSmallerComponents)!
let diff = cal.dateComponents([.day], from: today, to: nextBirthDay)
print(diff.day!)
答案 1 :(得分:4)
顺便说一下,如果有人需要这里是Swift 3中的@Aaron函数:
func daysBetween(date1: Date, date2: Date) -> Int {
let calendar = Calendar.current
let date1 = calendar.startOfDay(for: date1)
let date2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([Calendar.Component.day], from: date1, to: date2)
return components.day ?? 0
}