format a date in to the format october 13, 2014 11:13:00 am in swift

You can format a date object into the desired string format using a DateFormatter object in Swift. Here's an example code snippet to format a date into the format "October 13, 2014 11:13:00 AM":

main.swift
let date = Date() // get the current date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy h:mm:ss a" // set the desired date format
let dateString = dateFormatter.string(from: date)
print("Formatted date string:", dateString)
255 chars
6 lines

Output:

main.swift
Formatted date string: October 14, 2021 2:18:00 AM
51 chars
2 lines

In the dateFormat property of the DateFormatter, we have specified the format string using various symbols representing the components of the date and time.

  • MMMM: Full name of the month
  • d: Day of the month (no leading zeros)
  • yyyy: 4-digit year
  • h: Hour in 12-hour format (no leading zeros)
  • mm: Minute (with leading zeros)
  • ss: Second (with leading zeros)
  • a: AM/PM indicator

Note that we used MMMM instead of MM for the month symbol to get the full name of the month.

gistlibby LogSnag