Convert date string into proper format

后端 未结 2 1537
抹茶落季
抹茶落季 2021-01-29 15:41

I am getting a response from a server and there is a date string I need to convert into a date:

Thu Jun 29 07:15:25 +0000 2017

I am

2条回答
  •  庸人自扰
    2021-01-29 16:13

    You need to parse the date string into a Date object using a DateFormatter, then create a string from that Date using another DateFormatter with the output format you want to use.

    let created_at = "Thu Jun 29 07:15:25 +0000 2017"
    let df = DateFormatter()
    df.dateFormat = "E MMM dd HH:mm:ss Z yyyy"
    guard let date = df.date(from: created_at) else {return}
    let outputFormatter = DateFormatter()
    outputFormatter.dateFormat = "EEE, MMM d"
    let outputDate = outputFormatter.string(from: date)
    

    If you want to know what date formats look like, use NSDateFormatter.com, which has an interactive interface where you can play around with different date formats and have examples of most common formats as well.

提交回复
热议问题