Centralize lateness logic

- I finally put the app in the Travel category. xD
- I also moved the train lateness and arrival calculations into AmtrakDateFormatting from ContentView. I also renamed the timezone formatting parameters for clarity.
This commit is contained in:
Tony Bark 2026-08-24 21:05:11 -04:00
parent 79176585b4
commit e0077ec13b
3 changed files with 38 additions and 34 deletions

View file

@ -26,21 +26,21 @@ struct AmtrakDateFormatting {
return isoFormatter.date(from: isoString)
}
func time(from isoString: String?, timeZone: TimeZone?, relativeTo otherZone: TimeZone? = nil) -> String? {
func time(from isoString: String?, in zone: TimeZone?, comparedTo originZone: TimeZone? = nil) -> String? {
guard let isoString, !isoString.isEmpty, let date = isoFormatter.date(
from: isoString) else {
return nil
}
timeFormatter.timeZone = timeZone
timeFormatter.timeZone = zone
let formatted = timeFormatter.string(from: date)
guard
let timeZone,
let otherZone,
timeZone.identifier != otherZone.identifier,
let abbreviation = timeZone.abbreviation(for: date)
let zone,
let originZone,
zone.identifier != originZone.identifier,
let abbreviation = zone.abbreviation(for: date)
else {
return formatted
}
@ -48,6 +48,29 @@ struct AmtrakDateFormatting {
return "\(formatted) \(abbreviation)"
}
func isOnTime(actual: String?, scheduled: String?) -> TrainLateness {
guard
let actualDate = parsedDate(from: actual),
let scheduledDate = parsedDate(from: scheduled)
else {
return .unknown
}
let differenceInMinutes = Int(actualDate.timeIntervalSince(scheduledDate) / 60)
switch differenceInMinutes {
case -1...1:
return .onTime
case ..<0:
return .early(minutes: -differenceInMinutes)
default:
return .late(minutes: differenceInMinutes)
}
}
func localTime(timeZone: TimeZone?) -> String {
let now = Date()
timeFormatter.timeZone = timeZone