首页 > 解决方案 > 检查特定日期是否是今天(或过去)斯威夫特

问题描述

通过 dateformatter,我如何编写一个函数来了解特定日期是否已经过去或今天?

示例:2020 年 3 月 8 日

日期()

    if Date() >= 28March2020 {
      return true
    } else {
      return false
    } 

谢谢

标签: swiftnsdateformatter

解决方案


你可以做:

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 一天的开始之后。


推荐阅读