1

I am trying to convert the current time to an Int (without the AM/PM addition) and doing calculations with it. For instance, compare it to an older time and calculate the difference, then show the difference in hours:minutes. But I am really struggling here.

Getting the time:

func getTime() -> String {
    let formatter = DateFormatter()
    formatter.timeStyle = .long
    let dateString = formatter.string(from: Date())
    return dateString
}

I'd like to remove the AM/PM here.

Saving time to UserDefaults:

UserDefaults.standard.set(self.currentTime, forKey: "startTime")

Getting the saved time and current time and do some calculations here:

let startTime = UserDefaults.standard.integer(forKey: "startTime")
let currentTime = getTime()
let timeDiff = currentTime - startTime

Obviously this doesn't work because it's all strings. I know how to convert a string of integers to int: Int(getTime()) ?? 0 for instance, but as long as I cannot remove the AM/PM this all doesn't work of course.

What can I do or am I making this more difficult than it should be?

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Hej-j
  • 11
  • 2
  • 1
    Yes you are over complicating things, no need to involve strings in this. Here is one way to convert the date to a double, https://developer.apple.com/documentation/foundation/date/1779963-timeintervalsince1970. But you should really read up on the date and times classes that are available, maybe there’s even a better solution for you. https://developer.apple.com/documentation/foundation/dates_and_times – Joakim Danielson Apr 23 '23 at 10:49

2 Answers2

1

Here is another approach:

Date provides an API which returns the number of seconds (as TimeInterval / Double) since Jan 1, 2001.

Save this value to UserDefaults

UserDefaults.standard.set(Date().timeIntervalSinceReferenceDate, forKey: "startTime")

And read ist

let startTimeInterval = UserDefaults.standard.double(forKey: "startTime")
let startTime = Date(timeIntervalSinceReferenceDate: startTimeInterval)
let currentTime = Date().timeIntervalSinceReferenceDate
let timeDiff = currentTime - startTime

and display it with the appropriate formatter

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
let timeString = string(from: timeDiff)
print(timeString)
vadian
  • 274,689
  • 30
  • 353
  • 361
-1

I think it's better not do Date calculations in Int, use DateComponents instead. it provides Int values for all date components (day, hour,..). For specific string formats (e.g no am/pm) use DateFormatter.

tim
  • 537
  • 4
  • 7