简体   繁体   中英

Swift ISO8601 format to Date returning fatal error

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)
        }

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM