Search code examples
iosswiftdateformatter

Date Formatter in swift


i want to get this type of formate -> April 20, 2018 at 9:02:00 PM UTC+5:30 for firestore timestamp. i already try this code but do not get proper formate as above.

let date = Date()
let formatter = DateFormatter()

formatter.dateFormat = "MMMM d yyyy hh:mm:ss a Z"
formatter.timeZone = NSTimeZone(name: "IST") as TimeZone?

let result = formatter.string(from: date)
print(result)

already use this formatter formatter.dateFormat = "MMMM d yyyy'T'hh:mm:ss a Z"

Thanks


Solution

  • You can use like this:

        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm:ss a 'UTC'Z" //If you dont want static "UTC" you can go for ZZZZ instead of 'UTC'Z.
        formatter.timeZone = TimeZone(abbreviation: "IST")
        let result1 = formatter.string(from: date)
        print(result1)
    

    Note: If you do not want the UTC to be static in the string, you can also use the format "MMMM dd, yyyy 'at' hh:mm:ss a ZZZZ"

    Thank you Larme For the format improvement

    Output:

    enter image description here