【问题标题】:Testing for Anniversary Date using NSDate/NSCalendar使用 NSDate/NSCalendar 测试周年日期
【发布时间】:2015-10-27 22:51:00
【问题描述】:

我试图弄清楚如何确定今天是否是 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
    //      }

}

【问题讨论】:

    标签: swift nsdate nscalendar


    【解决方案1】:

    为了进行日期比较,在将 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)!")
        }
    }
    

    【讨论】:

    • 您可以在birthDays.filter({$0 == today}) 中将最后一个for 语句更改为birthDay 并删除if 检查
    • 太棒了!我以为我必须创建生日,然后将其拆分以进行比较。这要容易得多。谢谢!
    • 有一个问题(我认为)。如果此人的生日是 2 月 29 日,并且当年不是闰年,那么与今天的日期比较应该在 3 月 1 日为真。因此最好转换日期组件(一起与当前年份)到 NSDate 并使用 isDateInToday() 进行检查。
    • 我已经修改了答案。
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多