How do I format JSON Date String with Swift?

后端 未结 5 1659
Happy的楠姐
Happy的楠姐 2020-12-29 06:55

I make an http get request to a server and get back a json object with a date string like this:

{
    name = \"Place1\";
    temperature = 79;
    humidity =         


        
5条回答
  •  感情败类
    2020-12-29 07:39

    Here is my answer using extension in 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

提交回复
热议问题