如何解决如何在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。