23

How do I determine whether an NSDate (including time) has passed? I need to basically compare today's date to a date in the db but am stumped.

JOM
  • 8,139
  • 6
  • 78
  • 111
TheLearner
  • 19,387
  • 35
  • 95
  • 163

3 Answers3

92

Try this:

if ([someDate timeIntervalSinceNow] < 0.0) {
    // Date has passed
}
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • 13
    I put that into a category method so you can use `someDate.isInPast`. – Peter DeWeese Jan 05 '12 at 20:28
  • your code is comparing only date not the time. Like i am comparing same day but different time like this: 1/1/2015 5:00:00 and 1/1/2015 7:00:00 with this date it's showing me the Date has passed. – Deepak Aug 24 '15 at 10:36
  • 1
    +Daddy, not sure what you mean. According to the documentation this method should be perfect: "The time interval between the date object and the current date and time. (read-only) If the date object is earlier than the current date and time, this property’s value is negative." – Erik van der Neut Jun 08 '16 at 07:05
  • 1
    For use in Date Extension: `func isPast() -> Bool { if (self.timeIntervalSinceNow < 0.0) { return true } else { return false } }` – AppreciateIt Sep 04 '17 at 10:22
6

you need to use an NSDate comparison, many answers on here will assist you.

iOS: Compare two dates

logic will need tweaking, but this should set you in the right direction:

- (BOOL)date:(NSDate*)date isBefore:(BOOL)before otherDate:(NSDate*)otherDate ;
{
    if(before && ([date compare:otherDate] == NSOrderedAscending))
        return YES;
    if (!before && ([date compare:otherDate] == NSOrderedDescending))
        return YES;  
}

usage:

if([self date:yourDate isBefore:YES otherDate:[NSDate date]]) 
Community
  • 1
  • 1
Nik Burns
  • 3,363
  • 2
  • 29
  • 37
  • 4
    On a coding-style note: your second parameter should really be named something like `isBefore:`. Reading out loud "date:X isBefore:YES/NO otherDate:Y" sounds a lot better IMO than "date:X is:YES/NO otherDate:Y". – Taum Dec 16 '14 at 16:03
2

You can use

[NSDate date];

to get an NSDate object representing the current time and date.

Then compare that to the date you are analysing, for example:

if ([currentDate timeIntervalSince1970] > [yourDate timeIntervalSince1970]) {
// yourDate is in the past
}

you can use this to compare any two dates. Hope this helps.

Simon Withington
  • 1,485
  • 2
  • 11
  • 17
  • 1
    or do it inline: ([[NSDate date] timeIntervalSince1970] > [yourDate timeIntervalSince1970]) – Simon Withington Jan 05 '12 at 16:36
  • I was just providing a more general solution for comparing dates - comparing a date to now is rather a niche case. In practice though, you probably would just use timeIntervalSinceNow in this particular scenario. – Simon Withington Jan 05 '12 at 17:17