swift - 检查特定日期是否是今天(或过去)斯威夫特
问题描述
通过 dateformatter,我如何编写一个函数来了解特定日期是否已经过去或今天?
示例:2020 年 3 月 8 日
日期()
if Date() >= 28March2020 {
return true
} else {
return false
}
谢谢
解决方案
你可以做:
if Date() >= Calendar.current.dateWith(year: 2020, month: 3, day: 28) ?? Date.distantFuture {
return true
} else {
return false
}
其中dateWith(year:month:day:)
定义为:
extension Calendar {
func dateWith(year: Int, month: Int, day: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return date(from: dateComponents)
}
}
该方法基本返回Date
指定年、月、日的,时、分、秒分量均为0,即指定日的开始。换句话说,我正在检查现在是否在 2020-03-28 一天的开始之后。
推荐阅读
- arrays - vertx 决定 jsonobject vs jsonarray
- python-3.x - 使用 matplotlib(或 seaborn)绘制 d 轨道图
- git - 如何创建新分支并将来自另一个分支的差异合并到其中,但单个目录除外
- machine-learning - coremltools管道输入节点未连接到模型的其余部分
- r - 为什么我使用 which() 函数时会输出 integer(0)?
- visual-studio - Visual Studio 2017 版本 15.9.4 中的 C++ 优化器错误?
- c# - PrimaryThenSecondary LocationMode 是否检查主要的 RA-GRS 是否存在?
- sql - SQL - 获取多个范围之间的时间总和
- php - Codeigniter get_where 在条件数组中带有“或”
- javascript - 如何在 nodejs 中为 morgan 指定特定格式?