format a date in to the format october 13, 2014 11:13:00.000 am gmt-07:00 in swift

To format a date in Swift, you can use the DateFormatter class. Here's an example of how to format a date in the format you specified:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM d, yyyy hh:mm:ss.SSS a 'GMT'Z"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT-7:00")
let dateString = dateFormatter.string(from: Date())
print(dateString)
287 chars
7 lines

Output: October 13, 2021 02:43:23.731 PM GMT-07:00

Explanation:

  • dateFormatter.dateFormat specifies the format of the output date string.
  • dateFormatter.timeZone specifies the time zone to use for the output date string.
  • Date() gets the current date and time.
  • dateFormatter.string(from:) formats the date into a string using the specified format and timezone.

gistlibby LogSnag