dateformatter

How to convert a date string with optional fractional seconds using Codable in Swift4

白昼怎懂夜的黑 提交于 2019-11-26 05:16:09
I am replacing my old JSON parsing code with Swift's Codable and am running into a bit of a snag. I guess it isn't as much a Codable question as it is a DateFormatter question. Start with a struct struct JustADate: Codable { var date: Date } and a json string let json = """ { "date": "2017-06-19T18:43:19Z" } """ now lets decode let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let data = json.data(using: .utf8)! let justADate = try! decoder.decode(JustADate.self, from: data) //all good But if we change the date so that it has fractional seconds, for example: let json = """ {

How to convert a date string with optional fractional seconds using Codable in Swift4

北城余情 提交于 2019-11-26 00:48:54
问题 I am replacing my old JSON parsing code with Swift\'s Codable and am running into a bit of a snag. I guess it isn\'t as much a Codable question as it is a DateFormatter question. Start with a struct struct JustADate: Codable { var date: Date } and a json string let json = \"\"\" { \"date\": \"2017-06-19T18:43:19Z\" } \"\"\" now lets decode let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let data = json.data(using: .utf8)! let justADate = try! decoder.decode(JustADate.self,

How do I get the current Date in short format in Swift

。_饼干妹妹 提交于 2019-11-26 00:48:35
问题 In the images below you can see the code I wrote and the values of all the variables: class fun getCurrentShortDate() -> String { var todaysDate = NSDate() var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = \"dd-MM-yyyy\" var DateInFormat = dateFormatter.stringFromDate(todaysDate) return DateInFormat } Variable values As you can see the current date is found no problem, but when I try to change the NSDate to a string, it just won\'t do it. 回答1: Xcode 8 or later • Swift 3 or