本教程显示给定日期是否在当前日期之前或今天。
下面的例子只检查日期,不检查时间
在Swift中检查给定日期是否在今天之前?
当前日期使用new Date()对象返回。 你可以使用date方法创建过去和未来的日期。 它接受
byAdding:告诉你添加.day或任何数值:数值可以是正数或负数:指定当前日期。
日期可以使用< 操作符进行比较。
下面是一个例子,检查给定日期是否在当前日期之前
import Foundation
let date = Date()
let pastDate = Calendar.current.date(byAdding: .day, value: -1, to: date)!
print(date) //2022-07-03 06:13:45 +0000
print(pastDate)//2022-07-02 06:13:45 +0000
if(pastDate<date){
print("pastDate is before current date")
}
输出:
2022-07-03 06:13:45 +0000
2022-07-04 06:13:45 +0000
2022-07-02 06:13:45 +0000
pastDate is before current date
检查给定日期是否在swift中的今日日期之后?
日期的比较可以使用>来检查日期之后:
import Foundation
let date = Date()
let futureDate = Calendar.current.date(byAdding: .day, value: 1, to: date)!
print(date) //2022-07-03 06:13:45 +0000
print(futureDate)//2022-07-04 06:13:45 +0000
if(futureDate>date){
print("futureDate is before current date")
}
输出:
2022-07-03 06:13:45 +0000
2022-07-04 06:13:45 +0000
futureDate is before current date