首页 > 解决方案 > 斯威夫特:如何查看今天之后的日期?

问题描述

我想限制 date() 是否在今天两天之后,然后允许更改。

例如,今天是 2020 年 5 月 12 日,即 2020 年last_date5 月 15 日,限制是前 2 天。

因此,用户可以last_date在 2020 年 5 月 13 日或之前更改。

如果今天是 2020 年 5 月 14 日,则不允许用户更改last_date.

抱歉英语语法不好。

func可能是这样的:

func checkDate(_ last_date: Date) -> Bool {
    if //last_date() after today At least two days// {
        return true
    } else {
        return false
    }
}

标签: swiftdatedatetime

解决方案


一个很好的方法是这样的:

func checkDate(_ lastDate: Date) -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date(timeIntervalSinceNow: 0))

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        return false
    }
}

注意:日历返回的天数是可选的。我选择在返回 nil 时返回 false,但您可能更愿意通过抛出错误来处理它。然后,您将能够在视图控制器中处理该错误以通知用户。为此,您可以使用以下内容:

enum dateError: Error {
    case numberOfDays
}

func checkDate(_ lastDate: Date) throws -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date(timeIntervalSinceNow: 0))

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        throw dateError.numberOfDays
    }
}

但最终,在这种情况下,我更愿意抛出一个 fatalError。由于我们明确要求 dateComponents 提取日期,它应该返回它。所以我要做的是:

func checkDate(_ lastDate: Date) -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date())

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        fatalError("The number of days should not be nil.")
    }
}

推荐阅读