【问题标题】:Check for a new month using Date in Swift在 Swift 中使用 Date 检查新月份
【发布时间】:2025-11-23 17:10:01
【问题描述】:

我想在新的一个月开始后通知用户并重置应用的某个方面。每次更改月份时都需要重复此重置。

使用 Swift 并使用过 DateToolsSwift pod.Date Pod

什么是让它工作的最佳方法

【问题讨论】:

  • 到目前为止你尝试过什么?有什么我们可以帮助您的代码吗?
  • @fuzz 我在考虑每次应用程序启动时使用 userDefaults 来检查当前日期和上次保存的日期,如果月份不同,则在应用程序上执行重置。但我不喜欢使用用户默认值,所以希望有更好的方法。
  • 为什么不想使用UserDefaults?您想保存一点状态,而该 API 非常适合。手动将文件保存在某处是另一种选择,您可以携带不值得执行此任务的大枪(核心数据)等。
  • @gg11 我建议你试一试,如果你在实施它时遇到问题,那么你可以随时编辑你的问题,我们可以帮助你。

标签: ios swift date


【解决方案1】:
func checkIfNewMonth(newDate: Date, oldDate: Date){

    var userCalendar = Calendar.current
    userCalendar.timeZone = TimeZone(abbreviation: "UTC")!

    let oldComponents = userCalendar.dateComponents([.month, .year], from: oldDate)
    let newComponents = userCalendar.dateComponents([.month, .year], from: newDate)

    guard let oldCompareDate = userCalendar.date(from: oldComponents) else { return }
    guard let newCompareDate = userCalendar.date(from: newComponents) else { return }

    if newCompareDate > oldCompareDate {
        //New date is a new month
    } else if newCompareDate < oldCompareDate {
        //New date is an previous month
    }
}

我想我会发布一个功能来满足操作的要求。只需输入您要比较的两个日期。我认为 UserDefaults 也是存储旧日期的好方法。

【讨论】:

    【解决方案2】:

    日历can tell you the range of the current month。下个月从当月月底开始:

    let startOfNextMonth = Calendar.current.dateInterval(of: .month, for: Date())?.end
    let formatter = DateFormatter()
    formatter.dateStyle = .long
    print(startOfNextMonth.map(formatter.string(from:)) ?? "not a date")
    

    只需为此日期安排UNNotificationRequest

    【讨论】: