使用NSDate / NSCalendar测试周年日期

时间:2015-10-27 22:51:00

标签: swift nsdate nscalendar

我试图弄清楚如何确定今天是否是NSCalendar项目的周年纪念日。我发现的所有内容都将特定日期的月,日,年与另一个特定的月,日和年进行比较。粒度对我不利,因为它首先比较的是年份。

这是我到目前为止所得到的。我已经阅读了文档,但我遗漏了一些内容(基本的)。它是什么?

// get the current date
let calendar = NSCalendar.currentCalendar()
var dateComponents = calendar.components([.Month, .Day], fromDate: NSDate())

let today = calendar.dateFromComponents(dateComponents)

var birthDates = [NSDate]()

let tomsBirthday = calendar.dateWithEra(1, year: 1964, month: 9, day: 3, hour: 0, minute: 0, second: 0, nanosecond: 0)
birthDates.append(tomsBirthday!)

let dicksBirthday = calendar.dateWithEra(1, year: 1952, month: 4, day: 5, hour: 0, minute: 0, second: 0, nanosecond: 0)
birthDates.append(dicksBirthday!)

let harrysBirthday = calendar.dateWithEra(1, year: 2015, month: 10, day: 27, hour: 0, minute: 0, second: 0, nanosecond: 0)
birthDates.append(harrysBirthday!)

for birthday in birthDates {
    // compare the month and day to today's month and day
    // if birthday month == today's month {
    //      if birthday day == today's day {
    //             do something
    //      }

}

1 个答案:

答案 0 :(得分:2)

要进行日期比较,在非闰年将2月29日视为3月1日,您需要使用该人生日的月和日组成部分来构建当前年份的NSDate

另外,在构建NSDate比较日期时,请不要使用午夜作为时间。 Some days don't have a midnight in some time zones.改为使用正午。

struct Person {
    let name: String
    let birthYear: Int
    let birthMonth: Int
    let birthDay: Int
}

let people = [
    Person(name: "Tom", birthYear: 1964, birthMonth: 9, birthDay: 3),
    Person(name: "Dick", birthYear: 1952, birthMonth: 4, birthDay: 5),
    Person(name: "Harry", birthYear: 2015, birthMonth: 10, birthDay: 28)
]

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let todayComponents = calendar.components([.Era, .Year, .Month, .Day], fromDate: NSDate())
todayComponents.hour = 12
let todayNoon = calendar.dateFromComponents(todayComponents)

for person in people {
    let components = todayComponents.copy() as! NSDateComponents
    // DON'T copy person.birthYear
    components.month = person.birthMonth
    components.day = person.birthDay
    let birthdayNoon = calendar.dateFromComponents(components)
    if todayNoon == birthdayNoon {
        print("Happy birthday, \(person.name)!")
    }
}