Days between 2 NSDates in a calendar year swift

前端 未结 2 393
再見小時候
再見小時候 2020-12-21 03:58

I\'m building a birthday reminder app. I want the user to be able to see how many days it is until somebody\'s next birthday.

Let\'s say I have an NSDate()

相关标签:
2条回答
  • 2020-12-21 04:10

    Btw, in case anyone needs here is the @Aaron function in Swift 3:

    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
    }
    
    0 讨论(0)
  • 2020-12-21 04:14

    What you need is to compute the next occurrence of the (day and month component of the) birthday after today:

    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)!
    

    Remarks:

    • The purpose of the MatchNextTimePreservingSmallerUnits option is that if the birthday is on February 29 (in the Gregorian calendar), its next occurrence will be computed as March 1 if the year is not a leap year.

    • You might need to check first if the birthday is today, as it seems that nextDateAfterDate() would return the next birthday in that case.

    Then you can compute the difference in days as usual:

    let diff = cal.components(.CalendarUnitDay,
        fromDate: today,
        toDate: nextBirthDay,
        options: nil)
    println(diff.day)
    

    Update for 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)
    

    Update for 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!)
    
    0 讨论(0)
提交回复
热议问题