Time comparisons in swift

后端 未结 4 1098
梦如初夏
梦如初夏 2020-12-09 20:54

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.

相关标签:
4条回答
  • 2020-12-09 21:27

    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)
    
    0 讨论(0)
  • 2020-12-09 21:35

    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)
    
    0 讨论(0)
  • 2020-12-09 21:39

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

    0 讨论(0)
  • 2020-12-09 21:42
        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.
    
        }
    
    0 讨论(0)
提交回复
热议问题