简体   繁体   English

检查日期是否早于当前日期(Swift)

[英]Check if date is before current date (Swift)

I would like to check if a NSDate is before (in the past) by comparing it to the current date.我想通过将 NSDate 与当前日期进行比较来检查 NSDate 是否早于(过去)。 How would I do this?我该怎么做?

Thanks谢谢

I find the earlierDate method. 我找到了earlierDate方法。

if date1.earlierDate(date2).isEqualToDate(date1)  {
     print("date1 is earlier than date2")
}

You also have the laterDate method. 您还具有laterDate方法。

Swift 3 to swift 5: 迅捷3到迅捷5:

if date1 < date2  {
     print("date1 is earlier than date2")
}

There is a simple way to do that. 有一个简单的方法可以做到这一点。 (Swift 3 is even more simple, check at end of answer) (快速3更简单,请在答案末尾检查)

Swift code: SWIFT代码:

if myDate.timeIntervalSinceNow.isSignMinus {
    //myDate is earlier than Now (date and time)
} else {
    //myDate is equal or after than Now (date and time)
}

If you need compare date without time ("MM/dd/yyyy"). 如果您需要不带时间的比较日期(“ MM / dd / yyyy”)。

Swift code: SWIFT代码:

//Ref date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let someDate = dateFormatter.dateFromString("03/10/2015")

//Get calendar
let calendar = NSCalendar.currentCalendar()

//Get just MM/dd/yyyy from current date
let flags = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let components = calendar.components(flags, fromDate: NSDate())

//Convert to NSDate
let today = calendar.dateFromComponents(components)

if someDate!.timeIntervalSinceDate(today!).isSignMinus {
    //someDate is berofe than today
} else {
    //someDate is equal or after than today
} 

Apple docs link here . 苹果文档链接在这里

Edit 1: Important 编辑1:重要

From Swift 3 migration notes : 从Swift 3 迁移说明

The migrator is conservative but there are some uses of NSDate that have better representations in Swift 3: 迁移器是保守的,但是NSDate的某些用法在Swift 3中具有更好的表示形式:
(x as NSDate).earlierDate(y) can be changed to x < y ? x : y (x as NSDate).earlierDate(y)可以更改为x < y ? x : y x < y ? x : y
(x as NSDate).laterDate(y) can be changed to x < y ? y : x (x as NSDate).laterDate(y)可以更改为x < y ? y : x x < y ? y : x

So, in Swift 3 you be able to use comparison operators. 因此,在Swift 3中,您可以使用比较运算符。

If you need to compare one date with now without creation of new Date object you can simply use this in Swift 3: 如果您需要将一个日期与现在进行比较而不需要创建新的Date对象,则可以在Swift 3中简单地使用它:

if (futureDate.timeIntervalSinceNow.sign == .plus) {
    // date is in future
}

and

if (dateInPast.timeIntervalSinceNow.sign == .minus) {
    // date is in past
}

You don't need to extend NSDate here, just use "compare" as illustrated in the docs . 您无需在此处扩展NSDate,只需使用docs中所示的“ compare”即可。

For example, in Swift: 例如,在Swift中:

if currentDate.compare(myDate) == NSComparisonResult.OrderedDescending {
    println("myDate is earlier than currentDate")
}

You can extend NSDate to conform to the Equatable and Comparable protocols. 您可以扩展NSDate以符合EquatableComparable协议。 These are comparison protocols in Swift and allow the familiar comparison operators (==, <, > etc.) to work with dates. 这些是Swift中的比较协议,允许熟悉的比较运算符(==,<,>等)使用日期。 Put the following in a suitably named file, eg NSDate+Comparison.swift in your project: 将以下内容放入一个适当命名的文件中,例如,项目中的NSDate+Comparison.swift

extension NSDate: Equatable {}
extension NSDate: Comparable {}

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}

Now you can check if one date is before another with standard comparison operators. 现在,您可以使用标准比较运算符检查一个日期是否在另一个日期之前。

let date1 = NSDate(timeIntervalSince1970: 30)
let date2 = NSDate()

if date1 < date2 {
    print("ok")
}

For information on extensions in Swift see here . 有关Swift中扩展的信息,请参见此处 For information on the Equatable and Comparable protocols see here and here , respectively. 有关Equatable和Comparable协议的信息,请分别参见此处此处

Note : In this instance we're not creating custom operators, merely extending an existing type to support existing operators. 注意 :在这种情况下,我们不会创建自定义运算符,而只是扩展现有类型以支持现有运算符。

In Swift 4 you can use this code 在Swift 4中,您可以使用以下代码

if endDate.timeIntervalSince(startDate).sign == FloatingPointSign.minus {
    // endDate is in past
}

In Swift5 在Swift5中

    let nextDay = Calendar.current.date(byAdding: .day, value: -1, to: Date())
    let toDay = Date()
    print(toDay)
    print(nextDay!)

    if nextDay! < toDay  {
        print("date1 is earlier than date2")
    }


    let nextDay = Calendar.current.date(byAdding: .month, value: 1, to: Date())
    let toDay = Date()
    print(toDay)
    print(nextDay!)

    if nextDay! >= toDay  {
        print("date2 is earlier than date1")
    }

Here is an extension in Swift to check if the date is past date. 这是Swift中的扩展程序,用于检查日期是否为过期日期。

extension Date {
    var isPastDate: Bool {
        return self < Date()
    }
}

Usage: 用法:

let someDate = Date().addingTimeInterval(1)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print(date.isPastDate)
}

Since Swift 3, Dates are comparable so从 Swift 3 开始,日期具有可比性

if date1 < date2 { // do something }

They're also comparable so you can compare with == if you want.它们也具有可比性,因此您可以根据需要与==进行比较。

See Paul Hudson's Article on this.请参阅Paul Hudson对此的文章

we can use < for checking date:我们可以使用 < 来检查日期:

if myDate < Date() {

}

Made a quick Swift 2.3 function out of this 从中快速制作了Swift 2.3功能

// if you omit last parameter you comare with today
// use "11/20/2016" for 20 nov 2016
func dateIsBefore(customDate:String, referenceDate:String="today") -> Bool {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"

    let myDate = dateFormatter.dateFromString(customDate)
    let refDate = referenceDate == "today"
        ? NSDate()
        : dateFormatter.dateFromString(referenceDate)

    if NSDate().compare(myDate!) == NSComparisonResult.OrderedDescending {
        return false
    } else {
        return true
    }
}

Use it like this to see if your date is before today's date 像这样使用它来查看您的日期是否早于今天的日期

if dateIsBefore("12/25/2016") {
    print("Not Yet Christmas 2016 :(")
} else {
    print("Christmas Or Later!")
}

Or with a custom reference date 或带有自定义参考日期

if dateIsBefore("12/25/2016", referenceDate:"12/31/2016") {
    print("Christmas comes before new years!")
} else {
    print("Something is really wrong with the world...")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM