简体   繁体   中英

iOS || Swift || how to convert date response String to expeced timestamp

I have a date object whose type is String , and the value from backend response will be 2022-8-01T03:23:35.430+0000 , how can I convert it to the expected format like Mon, 1 Aug 2022, 3:23 pm

Thanks in advance!

Use DateFormatter

let dateString = "2022-8-01T03:23:35.430+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"

let date = dateFormatter.date(from: dateString)

print(date) // Date object

/// Date to String

let format = "EEE, d MMM YYYY, h:ss a" // format you need as a String
let formatter = DateFormatter()
formatter.dateFormat = format
//By default AM/PM symbols are uppercased
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
let label: String = formatter.string(from: date!)

print(label) // "Mon, 1 Aug 2022, 3:23 pm"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM