0

I made this extension of String to convert a string like "2018-10-04 23:12:42.640800" to another format. First I convert it to Date and then to String again.

extension String {
    func convertDateFormater(to: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS+00:00"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

        let dt = dateFormatter.date(from: self)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = to

        let completeDate = dt != nil ? dateFormatter.string(from: dt!):""

        return completeDate 
    }
}

For example:

let myNewDate = "2018-10-04 23:12:42.640800".convertDateFormater(to: "dd MMM yyyy")
print(myNewDate) //04 oct. 2018

This work marvelous on my iPhone but on my iPad it just crashes. I don't understand why. That's why I made the completeDate variable to stop the crash. But I need to change the format and it's not working.

Anybody know something about this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
AnaMM
  • 307
  • 4
  • 17
  • 1
    Possible duplicate of [What is the best way to deal with the NSDateFormatter locale "feechur"?](https://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feechur) – Tamás Sengel Oct 05 '18 at 23:12
  • 2
    Always set the formatter's locale to `en_US_POSIX` when parsing a date string with a fixes format. – rmaddy Oct 05 '18 at 23:17
  • I'm really surprised your code words on any device with the `+00:00` needlessly added to your date format. The string you are parsing does not have `+00:00` in it so your date format shouldn't have it either. – rmaddy Oct 05 '18 at 23:19
  • @rmaddy I know its wear to work, but it was the only way to transform that date, of course I fine how to transform from that formatter in other question of this page – AnaMM Oct 05 '18 at 23:42
  • @AnaMM is there an error message when it crashes? And what do you mean by *"I need to change the format and it's not working."*? – ielyamani Oct 05 '18 at 23:44
  • @Carpsen90 the only thing it say it's that the variable "dt" is nil, the wear thing its that only happen on the ipad. – AnaMM Oct 05 '18 at 23:47
  • Did you try removing `+00:00` as suggested in the previous comments? – ielyamani Oct 05 '18 at 23:50
  • are you sure that this is where you got your crash., coz this is working properly. maybe some iPhone only UI component having issues with iPad (eg. ActionSheet without popover) – RJE Oct 06 '18 at 10:57

0 Answers0