swift - 斯威夫特:如何查看今天之后的日期?
问题描述
我想限制 date() 是否在今天两天之后,然后允许更改。
例如,今天是 2020 年 5 月 12 日,即 2020 年last_date
5 月 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
}
}
解决方案
一个很好的方法是这样的:
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.")
}
}
推荐阅读
- python - 如何在 Pandas Dataframe Python 中按列总结每 3 行
- c - C指针声明之间的区别
- vb.net - vb.net用ms访问数据库datagrid视图可以更新数量
- file - 批量创建文件夹相同的文件名
- python-3.x - 如何更有效地使用来自 ipywidgets 的交互来绘制数据?
- r - R - 将数据帧的长度扩展为与另一个相似
- haskell - 我将如何实现这种情况 CallE 它将有 intrepeter 来测试函数调用?
- javascript - 在生成的表中创建唯一的单元格
- angular - 嵌套模块中的 APP_INITIALIZER 顺序
- c++ - C++ 模板模糊实例化