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.
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)
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)
Use timeIntervalSinceDate
of date on further date and pass the earlier date as parameter, this would give the time difference
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.
}