Swift ISO8601 format to Date

陌路散爱 提交于 2020-08-19 12:19:50

问题


I have the following string: 20180207T124600Z

How can I turn this into a Date object?

Here is my current code but it returns nil:

let dateString = "20180207T124600Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = .withFullTime
print(dateFormatter.date(from: dateString))

回答1:


You can specify ISO8601 date formate to the NSDateFormatter to get Date:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
print(dateFormatter.date(from: dateString)) //2018-02-07 12:46:00 +0000



回答2:


If you have a date such as:

let isoDate = "2018-12-26T13:48:05.000Z"

and you want to parse it into a Date, use:

let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
isoDateFormatter.formatOptions = [
    .withFullDate,
    .withFullTime,
    .withDashSeparatorInDate,
    .withFractionalSeconds]

if let realDate = isoDateFormatter.date(from: isoDate) {
    print("Got it: \(realDate)")
}

The important thing is to provide all the options for each part of the data you have. In my case, the seconds are expressed as a fraction.




回答3:


You need to specify the format options for the ISO8601DateFormatter to match your requirements (year, month, day and time), here is an example below:

//: Playground - noun: a place where people can play

import UIKit

let dateString = "20180207T124600Z"
let dateFormatter = ISO8601DateFormatter()

dateFormatter.formatOptions = [
    .withYear,
    .withMonth,
    .withDay,
    .withTime
]

print(dateFormatter.string(from: Date()))
print(dateFormatter.date(from: dateString))



回答4:


ISO8601DateFormatter should be something like

yyyy-MM-dd'T'HH:mm:ssZ

as long as your date string is in right format, it won't return nil.

as for formatOptions, it's Options for generating and parsing ISO 8601 date representations according Apple docs

Swift 4

in your example, it should be something like this:

let dateString = "2016-11-01T21:10:56Z"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: dateString)

let dateFormatter2 = ISO8601DateFormatter()
dateFormatter2.formatOptions = .withFullTime
print(dateFormatter2.string(from: date!))



回答5:


You can use following function to get date...

func isodateFromString(_ isoDate: String) -> Date? {

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
    return formatter.date(from: isoDate)
}


来源:https://stackoverflow.com/questions/48867030/swift-iso8601-format-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!