malcommac / SwiftDate

🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.
MIT License
7.61k stars 767 forks source link

Date formatter does not respect system time zone setting #784

Open skywalkerlw opened 3 years ago

skywalkerlw commented 3 years ago

I'm using the 6.3.1 version on Xcode 12.4 with iOS 14

My expectation:

Print local timestamp (my location is Australia)

let date = Date(timeIntervalSince1970: timestamp / 1000.0)
return date.toString(.custom("yyyy-MM-dd HH:mm:ss"))

What happened

Always show UTC timestamp (i tried on simulator and device, with locale setting correctly in iOS setting)

What I have tried

It works if I use vanilla way

let dateformatter = DateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
         dateformatter.timeZone = TimeZone.current
         let dateString = dateformatter.string(from: date)
chriswunsch00 commented 3 years ago

My location, UK, we are currently under BST (GMT +1).

My Expectation:

The toFormat should return 15:17.

What Happened

It is returning the incorrect time. From breakpointing func toFormat(_ format: String, locale: LocaleConvertible? = nil) -> String we see that the calendar is incorrect:

po region.calendar
▿ gregorian (fixed)
  - identifier : gregorian
  - kind : "fixed"
  ▿ locale : Optional<Locale>
    ▿ some : en_GB (autoupdatingCurrent)
      - identifier : "en_GB"
      - kind : "autoupdatingCurrent"
  ▿ timeZone : GMT (fixed)
    - identifier : "GMT"
    - kind : "fixed"
    ▿ abbreviation : Optional<String>
      - some : "GMT"
    - secondsFromGMT : 0
    - isDaylightSavingTime : false
  - firstWeekday : 2
  - minimumDaysInFirstWeek : 4

VS what the system outputs:

po Calendar.current
▿ gregorian (current)
  - identifier : gregorian
  - kind : "current"
  ▿ locale : Optional<Locale>
    ▿ some : en_GB (current)
      - identifier : "en_GB"
      - kind : "current"
  ▿ timeZone : Europe/London (fixed (equal to current))
    - identifier : "Europe/London"
    - kind : "fixed (equal to current)"
    ▿ abbreviation : Optional<String>
      - some : "BST"
    - secondsFromGMT : 3600
    - isDaylightSavingTime : true
  - firstWeekday : 2
  - minimumDaysInFirstWeek : 4

What I have tried:

Using this original date object:

2021-09-09 14:17:08 +0000

Trying to format it as such:

 let formattedTimestamp = timestamp!.toFormat("HH:mm", locale: NSLocale.current)

Returns:

14:17