Converting String to date Swfit 3

0

Hello, I'm trying to convert a String to Date in Swift 3. But the date is always returning me two more hours. Below is my code.

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    dateFormatter.locale =  Locale(identifier: "pt_BR")
    let date:Date = dateFormatter.date(from:"12-12-2017 16:49:19")!

Output: 2017-12-28 18:49:19 +0000

    
asked by anonymous 13.12.2017 / 12:54

1 answer

2

For your code to work with Locale of BR, you need to change the string "pt_BR" to "pt-br" , so you'll see that the date display will be correct.

You can better test this display by reporting some value to the timeZone property of dateFormatter, see the code below:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "pt-br")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date:Date = dateFormatter.date(from:"12-12-2017 16:49:19")!

In this example, the output will be -3h (ou -2h no horário de verão) for TimeZone that follows the Brasília time.

    
25.01.2018 / 20:17