10

Question:

I need to compare 2 times - the current time and a set one. If the set time is in the future, find out how many minutes remain until said future time.

Other Info:

I am currently using

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

which I stole from another answer on SO about how to get the current time in Int format. I then split the future time into hour (Int) and minutes(Int) and compare those... But that gets odd when you go over the hour barrier.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Byron Coetsee
  • 3,533
  • 5
  • 20
  • 31
  • 1
    See...http://stackoverflow.com/questions/5965044/how-to-compare-two-nsdates-which-is-more-recent and the first comment on that question.. – Jack Jun 19 '14 at 21:33

4 Answers4

23

You have compare function to compare 2 NSDate to know which one is more recent. It returns NSCompareResults

enum NSComparisonResult : Int {
    case OrderedAscending
    case OrderedSame
    case OrderedDescending
}

Get distance (in seconds) from 2 NSDate, you have .timeIntervalSinceDate(). Then, you know how to convert to minutes, hours, ...

let date1 : NSDate = ... 
let date2 : NSDate = ...

let compareResult = date1.compare(date2)

let interval = date1.timeIntervalSinceDate(date2)
Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
10

just to add to @tyt_g207's answer, I found the compare method, but hadn't found NSComparisonResult.OrderedDescending and the others. I used something like the modified below to check an expiration date against today's date

let date1 : NSDate = expirationDate 
let date2 : NSDate = NSDate() //initialized by default with the current date

let compareResult = date1.compare(date2)
if compareResult == NSComparisonResult.OrderedDescending {
    println("\(date1) is later than \(date2)")
}

let interval = date1.timeIntervalSinceDate(date2)
Michael
  • 2,973
  • 1
  • 27
  • 67
5
    let dateComparisionResult: NSComparisonResult = currentDate.compare("Your Date")


    if dateComparisionResult == NSComparisonResult.OrderedAscending
    {
        // Current date is smaller than end date.
    }
    else if dateComparisionResult == NSComparisonResult.OrderedDescending
    {
        // Current date is greater than end date.

    }
    else if dateComparisionResult == NSComparisonResult.OrderedSame
    {
        // Current date and end date are same.

    }
4

Use timeIntervalSinceDate of date on further date and pass the earlier date as parameter, this would give the time difference

nprd
  • 1,942
  • 1
  • 13
  • 16