如何使用 Swift 格式化 JSON 日期字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28748162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I format JSON Date String with Swift?
提问by Nearpoint
I make an http get request to a server and get back a json object with a date string like this:
我向服务器发出一个 http get 请求,并返回一个带有日期字符串的 json 对象,如下所示:
{
name = "Place1";
temperature = 79;
humidity = 68;
reported_at = "2013-07-21T19:32:00Z";
}
I want to format the reported_at key so I can display a readable date and time to the user.
我想格式化reported_at 键,以便向用户显示可读的日期和时间。
This is the swift code I am trying which keeps returning nil, as it cannot format the date.
这是我正在尝试的 swift 代码,它不断返回 nil,因为它无法格式化日期。
var str = "2013-07-21T19:32:00Z"
var dateFor: NSDateFormatter = NSDateFormatter()
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSS"
var yourDate: NSDate? = dateFor.dateFromString(str)
println(yourDate)
How can I format this date and time with Swift correctly? I want to display the date and time to the user so they can know when the reading was taken.
如何使用 Swift 正确格式化此日期和时间?我想向用户显示日期和时间,以便他们知道读取时间。
回答by Zell B.
Use the following string format to convert a server string into a Date
使用以下字符串格式将服务器字符串转换为日期
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
回答by vadian
Nowadays (September 2017) in Swift 4 there are smarter ways to decode ISO8601:
如今(2017 年 9 月)在 Swift 4 中有更聪明的方法来解码 ISO8601:
ISO8601DateFormatterlet str = "2013-07-21T19:32:00Z" let formatter = ISO8601DateFormatter() let yourDate = formatter.date(from: str)JSONDecoderstruct Place : Decodable { let name : String let temperature : Int let humidity : Int let reportedAt : Date } let json = """ {"name" : "Place1", "temperature" : 79, "humidity" : 68, "reported_at" : "2013-07-21T19:32:00Z"} """ let data = Data(json.utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase let place = try! decoder.decode(Place.self, from: data)
ISO8601DateFormatterlet str = "2013-07-21T19:32:00Z" let formatter = ISO8601DateFormatter() let yourDate = formatter.date(from: str)JSONDecoderstruct Place : Decodable { let name : String let temperature : Int let humidity : Int let reportedAt : Date } let json = """ {"name" : "Place1", "temperature" : 79, "humidity" : 68, "reported_at" : "2013-07-21T19:32:00Z"} """ let data = Data(json.utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase let place = try! decoder.decode(Place.self, from: data)
回答by Marchy
If you are using SwiftDate(you probably should!) simply use:
如果您正在使用SwiftDate(您可能应该!)只需使用:
Serialize:
连载:
let date:NSDate = ....
let dateInRegion = DateInRegion( absoluteTime: date )
let serializedString:String = dateInRegin.toString( .ISO8601Format( .Full ))!
Deserialize:
反序列化:
let serializedDate:String = "2016-03-01T22:10:55.200Z"
let date:NSDate? = serializedDate.toDateFromISO8601()
回答by Changnam Hong
Here is my answer using extensionin Swift4.
这是我使用extensionin 的答案Swift4。
extension String {
func toDate(dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let date: Date? = dateFormatter.date(from: self)
return date
}
Simple Usage
简单使用
let str = "2013-07-21T19:32:00Z";
let dateStr = str.toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ssZ")
Also, Check dateFormat that you want from here. ISO 8601
另外,从这里检查您想要的 dateFormat。ISO 8601
回答by Dilip Tiwari
For Converting JSONString to Date & Time in Swift 3.0Use Below Code:-
用于将JSON字符串转换为Swift 3.0使用以下代码的日期和时间:-
let timeinterval : TimeInterval = (checkInTime as! NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
print(dateFromServer)
let dateFormater : DateFormatter = DateFormatter()
//dateFormater.dateFormat = "dd-MMM-yyyy HH:mm a" // 22-Sep-2017 14:53 PM
dateFormater.dateFormat = "dd-MMM-yyyy hh:mm a" // 22-Sep-2017 02:53 PM
print(dateFormater.string(from: dateFromServer as Date))
where checkInTimewill be your String.Hope it will help someone
checkInTime你的字符串在哪里。希望它会帮助别人

