Search code examples
swiftdate-formatting

Swift Date Conversion Not Same Time


I am using the following function to convert a string into a date so that it can be converted to a different format using DateFormatter:

func changeDate(date1: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let date = dateFormatter.date(from:date1)!

    let dateFormatter2 = DateFormatter()
    dateFormatter2.dateFormat = "MMM-dd-yyyy / HH:mm zzz"
    let finaldate = dateFormatter2.string(from: date)

    return finaldate
}

I want to take a string that looks like 2017-08-29T11:49:19 and for it to display 08/29/2017 07:49 EDT as a string.


Solution

  • Date objects represent an absolute point in time. However, the string representations of Date objects generated using a DateFormatter do not represent an absolute point in time and hence they correspond to a specific time zone. When you use a DateFormatter without explicitly setting up a TimeZone, it defaults to the current timezone of the user.

    If you want to use your input string as a UTC timestamp, you need to set up the timeZone of your DateFormatter to UTC when generating the Date object. You should leave the timeZone of your second DateFormatter on the user's timeZone, which is the default value.

    func changeDate(date1: String) -> String {
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
        guard let date = dateFormatter.date(from:date1) else return {""}
    
        let outputDateFormatter = DateFormatter()
        outputDateFormatter.dateFormat = "MMM-dd-yyyy / HH:mm zzz"
        return outputDateFormatter.string(from: date)
    }