6 Replies
      Latest reply: Jan 24, 2017 11:47 AM by goldsdad RSS
      JayCo Level 1 Level 1 (5 points)



        I'm trying to compare two times against each other for a checkTimer method. I've got the functionality right, it's the 24 hour issue that's causing a problem.

        The functionality should be that if the current time is greater than the userDefault time then return true. The Bug exists where it's the next day. Am I better comparing two dates against each other or is there a simpler way.


        My method

        func checkTimer() -> Bool {
                let time = Int(currentTime())!
                let storedTime = Int(UserDefaults.standard.integer(forKey: "LastAccessTime"))
                if time >= storedTime {
                    print("Enough time has passed \(storedTime)")
                    return true
                print("Not enough time has passed \(storedTime)")
                return false
            func currentTime() -> String {
                let currentTime = Date()
                let formatter = DateFormatter()
                formatter.dateFormat = "Hmm"
                let time = formatter.string(from: currentTime)
                return "\(time)"


        • Re: Swift 3 Check Two times against each other help
          QuinceyMorris Level 6 Level 6 (2,465 points)

          You have to be more explicit about what you want — "time" is too ambiguous.


          A Date value is actually a date/time. If you want to compare the current date/time with the date/time at which something was last accessed, you should use the Date values, and not try to convert to strings or Ints. (Note: You can store a Date value in user defaults.) Such Date values are independent of time zone, daylight savings time, etc.


          If you mean a time of day, for example if you want to make a new backup of a file every day at a certain time, you're going to have to work a bit harder to deal with time zones, etc.