swiftunix-timestamp

Swift convert unix time to date and time gives incorrect year


I am getting time string from server but when I convert it to local time its giving incorrect

year like 52635

My code is-

if let dateVal = (model.insert_date){
            if dateVal != ""{
                
                //dateVal = "1598859638000"
                let dt = Double(dateVal)
                let date = Date(timeIntervalSince1970:dt!)
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "E MMM d yyyy"
                //dateFormatter.locale = Locale.init(identifier: "en")
                let outputDate = dateFormatter.string(from: date)
                print(outputDate) //Fri Nov 6 52635
               
                cell.lblName.text = outputDate
            }
        }

Solution

  • Divide timestamp by 1000, because Date uses seconds and the timestamp was generated with milliseconds and use TimeInterval instead of Double.

        let dateVal = TimeInterval(1598859638000) / 1000.0
    
        
        let date = Date(timeIntervalSince1970: TimeInterval(dateVal))
        print(date, "date", date.timeIntervalSince1970)
    
      
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.init(abbreviation: "en")
        dateFormatter.locale = Locale.init(identifier: "en")
        dateFormatter.dateFormat = "E MMM d yyyy"
        let outputDate = dateFormatter.string(from: date)
        print(outputDate) // Mon Aug 31 2020
    

    I guess your timestamp is generetd in a Java / Kotlin Applicatin. In java, (new Date(1598859638000l)) yields Mon Aug 31 2020.