iOS Swift 3 : Convert “yyyy-MM-dd'T'HH:mm:ssZ” format string to date object

后端 未结 3 1021
旧巷少年郎
旧巷少年郎 2020-12-05 19:18

Hello i have a dictionary

self.publishedAt = dictionary[\"publishedAt\"] as? NSString

in which i\'m getting date \"2017-01-27T18:36

3条回答
  •  抹茶落季
    2020-12-05 20:19

    Just used the function in your code(swift 4.2).

    public func convertDateFormatter(date: String) -> String {
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    dateFormatter.locale = Locale(identifier: "your_loc_id")
    let convertedDate = dateFormatter.date(from: date)
    
    guard dateFormatter.date(from: date) != nil else {
        assert(false, "no date from string")
        return ""
    }
    dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: convertedDate!)
    print(timeStamp)
    return timeStamp
    }
    

    Thanks

提交回复
热议问题