2016-11-17 164 views
14

运行时发生崩溃,指向dateFormmater.timezone。 在控制台的错误是:将Unix时间戳转换为日期为字符串? Swift

无法投型的值 'Swift.Optional'(0x1192bf4a8)到 'NSTimeZone'(0x1192c0270)。

rowEvents.date"1480134638.0"

我试着拉了Unix时间戳从火力地堡保存为一个字符串。将其转换为日期并再次保存为一个字符串,以便我可以将其发布到单元格标签上。

我从StackOverflow上得到这个代码。我插入我的数据,一切都很好,直到我运行它。我想一切是不是所有的好...

if let lastUpdated : String = rowEvents.date { 

    let epocTime = TimeInterval(lastUpdated)!/1000 // convert it from milliseconds dividing it by 1000 

    let unixTimestamp = NSDate(timeIntervalSince1970: epocTime) //convert unix timestamp to Date 

    let dateFormatter = DateFormatter() 
    dateFormatter.timeZone = NSTimeZone() as TimeZone! 
    dateFormatter.locale = NSLocale.current // NSLocale(localeIdentifier: "en_US_POSIX") 
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" 
    dateFormatter.date(from: String(describing: unixTimestamp)) 

    let updatedTimeStamp = unixTimestamp 
    let cellDate = DateFormatter.localizedString(from: updatedTimeStamp as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.medium) 

    cell.subtitleLabel.text = cellDate    
} 

结果从这个代码来到这里:

let myTimeStamp = self.datePicker?.date.timeIntervalSince1970 

let calendarDate = String(describing: myTimeStamp! /** 1000*/) 

回答

35

可以使用Date(timeIntervalSince1970:)转换unixTimestamp日期。

let unixTimestamp = 1480134638.0 
let date = Date(timeIntervalSince1970: unixTimestamp) 

如果你想要显示你可以使用DateFormatter像这样的字符串与特定的甲日期。

let date = Date(timeIntervalSince1970: unixtimeInterval) 
let dateFormatter = DateFormatter() 
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want 
dateFormatter.locale = NSLocale.current 
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want 
let strDate = dateFormatter.string(from: date) 
+0

'时区(简称: “GMT”)' - 终于,有人用'TimeZone'构造函数,而不是'NSTimeZone'那些拥有铸造。 – user28434

+1

非常感谢你的先生!那个顶尖的人解决了它,因为我不在乎什么格式。如果我需要某种格式,我肯定底部的代码也会。下次我需要做转换时,我会记住这两个代码! –

+0

@ReyCerio欢迎伴侣:) –

3

问题是行dateFormatter.timeZone = NSTimeZone() as TimeZone!

只需使用TimeZone,而不是像NSTimeZone
dateFormatter.timeZone = TimeZone.current,你的代码将工作。

您可能还会删除您的/ 1000,因为1480134638.0看起来更像是秒数而不是毫秒(自1970年以来)。

+0

谢谢先生!因为你的建议,我拿出了/ 1000。 –

+0

感谢您的建议!/1000后变得很好 – iDev750

相关问题