swiftdatensdateformatterdate-formatting

How to convert a date to a specific timezone when user is in a different timezone?


I have a problem in handling dates in Swift in different timezones. I'm getting an Italian date from my server and I'm trying to convert it into a Date through the following function:

func stringToDateTime(dateString: String) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    formatter.locale = Locale(identifier: "it_IT")
    formatter.timeZone = TimeZone(identifier: "Europe/Rome")
    return formatter.date(from: dateString)
}

However if the date is "2022-11-22 10:00:00", for example, and I'm in London or New York the function returns:

▿ 2022-11-22 09:00:00 +0000
- timeIntervalSinceReferenceDate : 690800400.0

Why is that so? I specified the timezone in the formatter so it should return me 10 o'clock. What am I doing wrong?


Solution

  • The date and time seems correct to me.

    The date and time which was passed "2022-11-22 10:00:00" is in Italian time, which is GMT+1, or with other words, 1 hour ahead of UTC.

    The date and time which was printed to the console is in UTC, or GMT+0, and is indicated by '+0000'.

    2022-11-22 09:00:00 +0000
    

    If we were to put this date into a converter for UTC to Italian time, we would get the initial value - "2022-11-22 10:00:00".

    When you print a Date in the console directly, it automatically uses UTC as the time zone. If you'd like to print a string representation of your Date object to the console in your locale, use this method:

    Generates a locale-aware string representation of a date using the default date format style.

    func formatted() -> String

    from Apple documentation: https://developer.apple.com/documentation/swift/sequence/formatted(_:)