Search code examples
swiftdate-formatting

can't convert time stamp date to string in swift 4


I'm trying to convert a timeStamp string date to Date.

The result always returns nil.

func getDatefromTimeStamp (str_date : String , strdateFormat: String) -> String { 
    // stringDate '2018-01-01T00:00:00.000+03:00' 
    let dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone! 


    let date = dateFormatter.date(from: str_date) 
    dateFormatter.dateFormat = strdateFormat 
    let datestr = dateFormatter.string(from: date!) 
    return datestr 
}

Solution

  • Your primary issue is that the format "yyyy-MM-dd'T'HH:mm:ssZ" does not match a string such as "2018-01-01T00:00:00.000+03:00". That string contains milliseconds but your format doesn't.

    Update your format to "yyyy-MM-dd'T'HH:mm:ss.SSSZ".

    That will fix the nil result.

    Then you should clean-up your use of NSTimeZone. Just use TimeZone.

    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    

    But there is no need to set the timezone when parsing this string because the string includes timezone information.

    However, you may or may not want a timezone set when converting the resulting Date into the new String. It depends on what result you want.

    Do you want the final string in UTC time (which is what you will get with your current code) or do you want the final string in the user's local time?

    If you want the final string in the user's local time, don't set the timezone property at all. It will default to local time.