1

I am trying to return an ISO8601 date and append it onto an array however I keep running into problems. For some reason I keep getting a fatal error as it finds nil while unwrapping an optional value. However I know the value is definitely in there. Am I formatting something incorrectly?

time_released format -> "2006-11-30T00:00:00.000Z"

if movieInfo.time_released != nil {

            let dateFormatter = ISO8601DateFormatter()
            let date = dateFormatter.date(from: movieInfo.time_released!)
            let dateString = dateFormatter.string(from: date!)

            array.append(dateString)
        }
unicorn_surprise
  • 951
  • 2
  • 21
  • 40

1 Answers1

3

The default ISO8601 formatter does not parse fractional seconds, so this returns nil when you try to parse the date string that includes them. If you want fractional seconds, you need to request them:

import Foundation

let time_released = "2006-11-30T00:00:00.000Z"

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions.insert(.withFractionalSeconds)
if let date = dateFormatter.date(from: time_released) {
    let dateString = dateFormatter.string(from: date)
    print(dateString)
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Hey Rob, this just returns the same exact thing for me. 2019-06-21T00:00:00.000Z How do I further format this into something more readable? – unicorn_surprise Jun 17 '19 at 22:51
  • It returns the same thing because it's being formatted with the same date formatter (that's what you were doing in your original code; I just brought it along). If you want a different format, create a new DateFormatter and configure it the way you want. – Rob Napier Jun 18 '19 at 13:35