amtkstat/Sources/AmtrakStatus/AmtrakDateFormatting.swift
Tony Bark a43eefadc1 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.
2026-08-24 03:09:49 -04:00

57 lines
1.6 KiB
Swift

import Foundation
struct AmtrakDateFormatting {
let isoFormatter = ISO8601DateFormatter()
let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter
}()
func parsedDate(from isoString: String?) -> Date? {
guard let isoString, !isoString.isEmpty, let date = isoFormatter.date(
from: isoString) else {
return nil
}
return isoFormatter.date(from: isoString)
}
func time(from isoString: String?, timeZone: TimeZone? = nil) -> String? {
guard let isoString, !isoString.isEmpty, let date = isoFormatter.date(
from: isoString) else {
return nil
}
timeFormatter.timeZone = timeZone
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 {
return nil
}
return dateFormatter.string(from: date)
}
}