skip to Main Content

So I have a date like this:

let date = Date()

Lets say that the date is 12.08.2021 14:40. I want to check and do stuff if there is more then 25 minutes past that date. How can I do this?

3

Answers


  1. You can use timeIntervalSinceNow and measure the difference (in seconds)

    let previousDate = Date().advanced(by: -1000)
    print("previous: (previousDate)")
    
    if -previousDate.timeIntervalSinceNow > 25 * 60 {
        print("past 25 minutes")
    } else {
        print("not past 25 minutes")
    }
    

    This example is relative, so will always print "not past 25 minutes" – however previousDate would be the actual previous date.

    Login or Signup to reply.
  2. The below function will allow you to check if the elapsed time since a previous date is more than a specific number of minutes.

    func intervalSince(_ previous: Date, isMoreThan minutes: Int) -> Bool {
       return Date() > previous.advanced(by: Double(minutes) * 60.0)
    }
    

    Note: This method only works with iOS 13 and above.

    Login or Signup to reply.
  3. I made this function. you use date.timeAgoSince(). This confirms how many minutes ago your variable was.

    
      extension Date {
            func timeAgoSince() -> String {
            
                let calendar = Calendar.current
                let now = Date().datePickerToString().stringToDate()
                let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
                let components = (calendar as NSCalendar).components(unitFlags, from: self, to: now, options: [])
    
                if let minute = components.minute, minute >= 1 {
                    return "past (minute) minutes"
                }
    
                return "now"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search