如何在 Swift 中的某个日期每年重复出现倒计时

How to have reoccurring countdown each year to a date in Swift

我正在尝试在我的 Swift 应用程序中加入假期倒计时功能,但在日期过后计时器变为负数时遇到了问题。倒计时应在日期过后重置。我做错了什么?

var holidayDate: Date {
    let currentYear = Date()
    let userCalendar = Calendar.current
    var components = DateComponents()
    components.year = userCalendar.component(.year, from: currentYear)
    components.day = 02
    components.month = 11
    
    return userCalendar.date(from: components)!
}

var today: Date {
    let now = Date()
    let userCalendar = Calendar.current
    var components = DateComponents()
    components.year = userCalendar.component(.year, from: now)
    components.day = userCalendar.component(.day, from: now)
    components.month = userCalendar.component(.month, from: now)
    
    return userCalendar.date(from: components)!
}

func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
    let calendar = Calendar.current
    let components = calendar.dateComponents([.day], from: startDate, to: endDate)
    return components.day!
}

您可以简单地使用日历 nextDate 方法来获取下一个日期匹配组件并将月和日组件传递给它:

func daysUntilNextDate(matching components: DateComponents) -> Int {
    let date = Date()
    guard let calendar = components.calendar,
          let nextDate = calendar.nextDate(after: date, matching: components, matchingPolicy: .strict) else { return .zero }
    return calendar.dateComponents([.day], from: date, to: nextDate).day!
}

let holiday: DateComponents = .init(calendar: .current, month: 11, day: 2)
let christmas: DateComponents = .init(calendar: .current, month: 12, day: 25)

daysUntilNextDate(matching: holiday)   // 363
daysUntilNextDate(matching: christmas) // 51