Check if date is before current date (Swift)
Asked Answered
V

12

69

I would like to check if a NSDate is before (in the past) by comparing it to the current date. How would I do this?

Thanks

Violaviolable answered 7/11, 2014 at 18:9 Comment(1)
Show the attempts you've already made at solving the problem.Seko
C
166

I find the earlierDate method.

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

You also have the laterDate method.

Swift 3 to swift 5:

if date1 < date2  {
     print("date1 is earlier than date2")
}
Camala answered 26/1, 2016 at 19:51 Comment(5)
Thanks, I'll take a look at that.Violaviolable
this seems to return a date rather than a booleanAtween
swift3 makes it simpler : simply use the < operatorEmmie
Could it be that those methods don't exist any more?Callus
The second one is still valid under swift 5Camala
V
39

If you need to compare one date with now without creation of new Date object you can simply use this in Swift 3:

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

and

if (dateInPast.timeIntervalSinceNow.sign == .minus) {
    // date is in past
}
Vogler answered 9/4, 2017 at 7:58 Comment(2)
this should have been the accepted answer more readable and makes more senseSmashed
Agreed with @Amma. This answer worked the best for me.Youmans
E
36

There is a simple way to do that. (Swift 3 is even more simple, check at end of answer)

Swift code:

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").

Swift code:

//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

From Swift 3 migration notes:

The migrator is conservative but there are some uses of NSDate that have better representations in Swift 3:
(x as NSDate).earlierDate(y) can be changed to x < y ? x : y
(x as NSDate).laterDate(y) can be changed to x < y ? y : x

So, in Swift 3 you be able to use comparison operators.

Etienne answered 11/3, 2015 at 14:23 Comment(0)
P
12

You don't need to extend NSDate here, just use "compare" as illustrated in the docs.

For example, in Swift:

if currentDate.compare(myDate) == NSComparisonResult.OrderedDescending {
    println("myDate is earlier than currentDate")
}
Penguin answered 20/2, 2015 at 17:58 Comment(2)
And could you elaborate to a noob like me, how you set your myDate variable before that? Does it have to be in a specific way, is it an INT or not? Really looking forward to your feedback.Misogamy
@MichelKapelle myDate is an instance of NSDate. Check the link which nick added, and you'll see this in the docs: func compare(_ other: NSDate) -> NSComparisonResult, hence: other is myDate.Plowboy
D
9

You can extend NSDate to conform to the Equatable and Comparable protocols. These are comparison protocols in Swift and allow the familiar comparison operators (==, <, > etc.) to work with dates. Put the following in a suitably named file, e.g. NSDate+Comparison.swift in your project:

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. For information on the Equatable and Comparable protocols see here and here, respectively.

Note: In this instance we're not creating custom operators, merely extending an existing type to support existing operators.

Disoblige answered 7/11, 2014 at 18:37 Comment(0)
G
4

Here is an extension in Swift to check if the date is past date.

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

Usage:

let someDate = Date().addingTimeInterval(1)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print(date.isPastDate)
}
Galatea answered 21/10, 2019 at 14:34 Comment(0)
C
3

In 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")
    }
Cabbala answered 23/8, 2019 at 5:29 Comment(0)
F
2

In Swift 4 you can use this code

if endDate.timeIntervalSince(startDate).sign == FloatingPointSign.minus {
    // endDate is in past
}
Felizio answered 3/12, 2018 at 13:5 Comment(0)
S
2

we can use < for checking date:

if myDate < Date() {

}
Servetnick answered 12/9, 2022 at 13:23 Comment(0)
E
0

Since Swift 3, Dates are comparable so

if date1 < date2 { // do something }

They're also comparable so you can compare with == if you want.

Erasion answered 23/12, 2021 at 21:28 Comment(0)
A
0

Upgrading Vagner's answer to Swift 5:

import Foundation

//Ref date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"


//Get calendar
let calendar = NSCalendar.current

//Get just MM/dd/yyyy from current date
let flags: Set<Calendar.Component> = [Calendar.Component.day, Calendar.Component.month, Calendar.Component.year]
let components = calendar.dateComponents(flags, from: Date())

//Convert to NSDate

if let today = calendar.date(from: components), let someDate = dateFormatter.date(from: "03/10/2015"), someDate.timeIntervalSince(today).sign == .minus {
  //someDate is berofe than today
} else {
  //someDate is equal or after than today
} 
Advertise answered 6/2, 2023 at 6:2 Comment(0)
R
-1

Made a quick Swift 2.3 function out of this

// 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...")
}
Rackley answered 12/12, 2016 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.