2

I'm trying to format a string(ex. Tue, 16 Jan 2018 | 05:34 PM) to date and then convert it back to string(ex. 2018-01-16 17:34:00) with different format by using following code.

let dateFormatterOne = DateFormatter()
dateFormatterOne.dateFormat = "E, d MMM yyy | hh:mm a"
dateFormatterOne.locale = Locale(identifier: "en_US_POSIX")
let dateFromString = dateFormatterOne.date(from: string)

let dateFormatterTwo = DateFormatter()
dateFormatterTwo.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = dateFormatterTwo.string(from: dateFromString!)

This seems to be working well in simulator but when I tested it on an iPod Touch running iOS 9 it doesn't give date in the first conversion so it becomes nil and crashes.

N4SK
  • 700
  • 8
  • 25
  • 1
    What is the locale on the iOS 9 device? If it's not set to English it will fail. – rmaddy Jan 12 '18 at 06:34
  • 1
    Set Current locale to English dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale! – Taimoor Suleman Jan 12 '18 at 06:37
  • it's still producing nil after I added the line dateFormatterOne.locale = Locale(identifier: "en_US_POSIX")... does it matter if i put it before or after setting dateFormat – N4SK Jan 12 '18 at 06:45
  • Try `"EEE, d MMM yyyy | hh:mm a"`. The order of setting the locale and format shouldn't matter but it can't hurt to try both ways. – rmaddy Jan 12 '18 at 07:00
  • i did but still the same result – N4SK Jan 12 '18 at 07:01
  • Is it possible the string has some extra whitespace such as a newline? As `print("\"\(string)\"")` and see if there is anything unexpected. – rmaddy Jan 12 '18 at 07:10
  • it's not that either but I solved it by programmatically extracting each part from the string and making a new date from that using DateComponents() instance. – N4SK Jan 12 '18 at 08:43

0 Answers0