Search code examples
stringdateformatter

Get the hour right in Swift


Im trying with a String to Date formatter but have been getting it wrong. Calling the function like this:

self.stringToDate(date: "26 10 1995 10:54:00")

This is the Function:

func stringToDate(date: String) -> Date {
        print(date)
        let formatter4 = DateFormatter()
        formatter4.dateFormat = "dd MM yyyy HH:mm:ss"
        return formatter4.date(from: date)!
    }

And this is the result in console:

26 10 1995 10:54:00
1995-10-26 16:54:00 +0000

Solution

  • check

    import Foundation
    
    let form = DateFormatter()
    form.dateFormat = "dd MM yyyy HH:mm:ss"
    print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
    
    form.timeZone = TimeZone(abbreviation: "UTC")
    print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
    
    form.timeZone = TimeZone(abbreviation: "EST")
    print(form.timeZone, form.date(from: "26 10 1995 10:54:00") ?? "")
    

    it prints

    Optional(Europe/Bratislava (current)) 1995-10-26 09:54:00 +0000
    Optional(GMT (fixed)) 1995-10-26 10:54:00 +0000
    Optional(America/New_York (fixed)) 1995-10-26 14:54:00 +0000