Show local station time; reuse date formatter

- Added localTime(timeZone:) and updateTime(timeZone:) to AmtrakDateFormatting to format the current time for a given timezone.
- In ContentView, make AmtrakDateFormatting is now a shared property with localTimeZone being used at the bottom to show "It is <time> at <station> station".
- trainStatus now saves the station name and timezone (avoiding repeated formatter instantiation) and isOnTime uses the shared formatter.
This commit is contained in:
Tony Bark 2026-08-24 03:09:49 -04:00
parent 791f261fc7
commit a43eefadc1
2 changed files with 19 additions and 5 deletions

View file

@ -35,6 +35,17 @@ struct AmtrakDateFormatting {
return timeFormatter.string(from: date)
}
func localTime(timeZone: TimeZone?) -> String {
let now = Date()
timeFormatter.timeZone = timeZone
return timeFormatter.string(from: now)
}
func updateTime(timeZone: TimeZone?) {
let now = Date()
timeFormatter.timeZone = timeZone
}
func date(from isoString: String?) -> String? {
guard let isoString, !isoString.isEmpty, let date = isoFormatter.date(
from: isoString) else {

View file

@ -10,7 +10,9 @@ struct ContentView: View {
@State var isLoading = false
@State var errorMessage: String?
@State var currentStation: String = ""
@State var localTimeZone: TimeZone?
let amtrakDate = AmtrakDateFormatting()
let unknown = "Unknown"
var body: some View {
@ -79,7 +81,9 @@ struct ContentView: View {
if let errorMessage {
Text(errorMessage)
} else if !currentStation.isEmpty {
Text(currentStation)
Text(
"It is \(amtrakDate.localTime(timeZone: localTimeZone)) at \(currentStation) station"
)
}
}.padding(10)
}
@ -162,8 +166,7 @@ struct ContentView: View {
}
func isOnTime(arr: String?, schArr: String?) -> TrainLateness {
let amtrakDate = AmtrakDateFormatting()
guard
let actualDate = amtrakDate.parsedDate(from: arr),
let scheduledDate = amtrakDate.parsedDate(from: schArr)
@ -185,7 +188,6 @@ struct ContentView: View {
func trainStatus(for train: Train, atStationCode code: String, timeZone: TimeZone?) -> TrainStatusRow {
let leg = train.stations?.first { $0.code == code }
let amtrakDate = AmtrakDateFormatting()
let stationName = leg?.name ?? unknown
let arrival = amtrakDate.time(from: leg?.arr, timeZone: timeZone) ?? amtrakDate.time(
from: leg?.schArr,
@ -194,7 +196,8 @@ struct ContentView: View {
from: leg?.schDep,
timeZone: timeZone)
currentStation = "\(stationName) station"
currentStation = stationName
localTimeZone = timeZone
return TrainStatusRow(
trainID: train.trainID,