Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. How would I do this?

Thanks

like image 807
Tom Coomer Avatar asked Nov 07 '14 18:11

Tom Coomer


3 Answers

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")
}
like image 167
Kibo Avatar answered Oct 22 '22 02:10

Kibo


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.

like image 36
Vagner Avatar answered Oct 22 '22 00:10

Vagner


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
}
like image 35
192kb Avatar answered Oct 22 '22 00:10

192kb