Converting String to date Swfit 3

Asked

Viewed 1,138 times

0

Hello, I’m trying to convert a String in Date in Swift 3. However the date is always returning me with two hours more. 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")!

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

  • Here it looks ok: http://tpcg.io/bhwp9W. Maybe you’re misconcepting what you need to do or you have wrong computer setup Other: https://swift.sandbox.bluemix.net/#/repl/5a311de352fd1304fcf3a6c0.

  • Strange, because I am compiled on iphone and when I get Timezone, appears America/ Sao Paulo, all straight.

1 answer

2


For your code to work with Locale BR, it is necessary to change the string "pt_BR" for "pt-br", with this you will see that the date display will be correct.

You can better test this view by stating some value to the property timeZone 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 the Timezone that follows the schedule of Brasilia.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.