检查日期是否在下个月

Check if date is in coming month

我正在为某个 birthdayTextField 设置一个日期,就像这样

@objc func birthdayDatePickerValueChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .none
    birthdayTextField.text = formatter.string(from: sender.date)

}

现在这个文本字段值存储在 coredata 的字符串属性中。 coredata 中可以存储很多这样的生日日期。现在,当我从数据库中获取这些日期时,我只想在表格视图中显示下个月的那些日期。

如何实现...?

这是一个在 Date 扩展中使用 CalendarDateComponents 强大的日期数学能力的解决方案。

  • 它计算下个月的第一天 nextDate(after:matching:matchingPolicy:) 寻找 day == 1
  • 它将给定日期与下个月的第一个日期进行比较 month 粒度 compare(:to:toGranularity:)

extension Date {
    func isDateInNextMonth() -> Bool {
        let calendar = Calendar.current
        let nextMonth = calendar.nextDate(after: Date(), matching: DateComponents(day:1), matchingPolicy: .nextTime)!
        return calendar.compare(self, to: nextMonth, toGranularity: .month) == .orderedSame
   }
}

在你的方法中简单地使用它

sender.date.isDateInNextMonth()

或者 – 更通用 – 根据其他 isDateIn... 方法作为 Calendar

的扩展
extension Calendar {
    func isDateInNextMonth(_ date : Date) -> Bool {
        let nextMonth = self.nextDate(after: Date(), matching: DateComponents(day:1), matchingPolicy: .nextTime)!
        return self.compare(date, to: nextMonth, toGranularity: .month) == .orderedSame
    }
}

并使用它

Calendar.current.isDateInNextMonth(sender.date)

编辑:

如果你想检查日期是否在接下来的 30 天内,它仍然更容易

extension Calendar {
    func isDateInNextThirtyDays(_ date : Date) -> Bool {
        return self.dateComponents([.month], from: Date(), to:date).month! < 1
    }
}