Wrong TimeZone in SPM package, correct when created locally in App

Hi,

I have a weird issue I can't figure out (hope this is the correct forum for it). I've implemented an SPM package which contains DateFormatter extensions. When implementing this DateFormatter:

static let time: DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = .current
    formatter.timeZone = .current
    formatter.dateFormat = "HH:mm"
    return formatter
  }()

I have the same implementation in a SwiftUI View or ViewModel in the main app. When I compare the TimeZone between the DateFormatter created locally or in the SPM package there's a difference in TimeZone, see attached screenshot.

The top one is the locally created DateFormatter (same implementation) and the bottom one is the DateFormatter that's created in the SPM library.

I tried using .autoUpdatingCurrent on the TimeZone and also the setLocalizedDateFormatFromTemplate() but that doesn't change to the correct TimeZone.

Any idea what could cause this behaviour?

When I compare the TimeZone between the DateFormatter created
locally or in the SPM package there's a difference in TimeZone, see
attached screenshot.

I’d like to clarify this. To see different behaviour you have to have different execution environments. An “[SwiftPM] package” isn’t an execution environment, it’s just a bunch o’ code. To see its behaviour, you have to run it. How are you running it?

If you load the SwiftPM code into your SwiftUI app, I’d be very surprised if it behaved differently from the code that’s built in to that app.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

Thanks for your reply! I think I've found out what the problem is, I'm using this method to change the TimeZone:

func set(timeZone: TimeZone? = nil, locale: Locale = .current) -> DateFormatter {
        self.timeZone = timeZone ?? .current
        self.locale = locale
        return self
}

Since all the DateFormatters are static, when changing the TimeZone on a DateFormatter somewhere else it'll be changed everywhere since there's only one instance. I tested this in a playground and it is exactly the behaviour I have in my app. So it has nothing to do with SPM packages, it's just the method I created which breaks it.