Search code examples
swiftdatetimestampnsdateformatter

Swift date formatter off by one day


It's pretty bizarre. If I look at the Data object it correctly has 01/01/1990, but when converting it to a string it returns 12/31/1989. This seems to have only recently started happening as the code in question is very old/well used at this point.

let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
        
let date = Date(timeIntervalSince1970:timestamp)
return dateFormatter.string(from: date) as NSString

Value being passed in is 631152000


Solution

  • try setting the TimeZone that you want, for example:

     dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) 
    

    or

    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")