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!
CodePudding user response:
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"