我想弄清楚今天是否是某人的生日。以生日为参数。
检查自出生日期以来的天数是否可以被365整除而不休息。显然,由于使用366天的年份,该操作将失败。
比较今天和生日的日期和月份属性。这种方法不适用于2月29日出生的人。基本上,问题又是the年。
有人知道当前日期是否是生日的简便方法吗?
答案 0 :(得分:1)
如果您的生日是2月29日,那么打算使用什么逻辑来回答以下问题:“今天您的生日是非?年吗?”。这不是显而易见的事情。我最好能想到的是2月28日是您的生日,除非今年是a年,在这种情况下2月29日是您的生日。
您可以simply ask for how many days are in February this year,然后做一些简单的逻辑来假装生日实际上是非leap年的28岁。
// Psuedo code
var bday = someUser.bday
if (bday.month == 2 && bday.date == 29 && daysInFebruraryThisYear == 28) {
bday.date = 28
}
// Is it today?
return bday.month == today.month && bday.date == today.date
答案 1 :(得分:0)
另一种解决方案是将月/日日期转换为当前日历并从那里进行比较:
let actualBirthDate = Date(year: 2000, month: 2, day: 29)
// Created 'currentDate' as a non-leap year for testing,
// but you would want to use 'Date()' here for your app
let currentDate = Date(year: 2001, month: 3, day: 1)
var birthDateComponents = Calendar.current.dateComponents([.year, .month, .day], from: actualBirthDate)
let currentDateComponents = Calendar.current.dateComponents([.year, .month, .day], from: currentDate)
// Plot the birthdate on this year's calendar.
// Feb.29 will convert to Mar.1 on a non-leap year.
birthDateComponents.year = currentDateComponents.year
if let birthday = Calendar.current.date(from: birthDateComponents) {
var birthdayComponents = Calendar.current.dateComponents([.year, .month, .day], from: birthday)
// Now if day and month match, we know it's your birthday
if birthdayComponents.month == currentDateComponents.month && birthdayComponents.day == currentDateComponents.day {
print("Happy birthday!")
}
}
修改currentDate
以尝试不同的年份(或在完成时将其设置为Date()
)。 2月29日将在非ap年转换为3月1日,但在leap年则保持不变。
如果您想知道我使用的Date初始值设定项,那么我只有一个Date扩展名,如下所示:
extension Date {
init(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, millisecond: Int? = nil, timeZone: TimeZone? = nil) {
let now = Date()
var dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: now)
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
dateComponents.nanosecond = 1000000 * (millisecond ?? 0)
if let timeZone = timeZone {
dateComponents.timeZone = timeZone
}
guard let date = Calendar.current.date(from: dateComponents) else {
fatalError("Failed to construct date")
}
self.init(timeInterval: 0, since: date)
}
}