Swift 将 UNIX 时间转换为日期,时间给出了错误的年份

iDe*_*per 2 unix-timestamp swift

我从服务器获取时间字符串,但是当我将其转换为本地时间时,它给出的值不正确

年如52635

我的代码是-

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
            }
        }
Run Code Online (Sandbox Code Playgroud)

mah*_*han 5

将时间戳除以1000,因为 Date 使用秒,而时间戳是用毫秒生成的,并使用TimeInterval而不是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
Run Code Online (Sandbox Code Playgroud)

我猜你的时间戳是在 Java / Kotlin 应用程序中生成的。在java中, (new Date(1598859638000l))产生Mon Aug 31 2020