Search code examples
iosswiftswift3nsdateformatter

How to convert "2017-07-11T06:52:15.948Z" in to like "JUL, 7 2017" in swift


I'm trying to convert string to date, and again date to string.

I tried below, but it gives me a nil value error

let string = "2017-07-11T06:52:15.948Z"

let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale // save locale temporarily
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = tempLocale // reset the locale
let dateString = dateFormatter.string(from: date)
print("EXACT_DATE : \(dateString)")

then I tried to use only the date without time by seperating the exact string like below

let string = "2017-07-11T06:52:15.948Z"
let dateonly = (string.components(separatedBy: "T"))[0]
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-mm-dd"
dateformatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
let date = dateformatter.date(from: dateonly!)

print(date ?? "no date ")


dateformatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateformatter.string(from: date!) //pass Date here
print(newDate)

this works fine. but show me the wrong month

hope your help with this


Solution

  • for reference purpose I taken the answer from here for append the milliseconds SSS

    just change the date format

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    

    to

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    

    for full code

       let string = "2017-07-11T06:52:15.948Z"
        let dateFormatter = DateFormatter()
        let tempLocale = dateFormatter.locale // save locale temporarily
        dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let date = dateFormatter.date(from: string)!
        dateFormatter.dateFormat = "MMM d, yyyy" ; //"dd-MM-yyyy HH:mm:ss"
        dateFormatter.locale = tempLocale // reset the locale --> but no need here
        let dateString = dateFormatter.string(from: date)
        print("EXACT_DATE : \(dateString)")
    

    output

    enter image description here