我在跑步时遇到崩溃,它指向dateFormmater.timezone。控制台中的错误是:
dateFormmater.timezone
无法将类型“ Swift.Optional”(0x1192bf4a8)的值强制转换为“ NSTimeZone”(0x1192c0270)。
价值rowEvents.date就是"1480134638.0"
rowEvents.date
"1480134638.0"
我试图从Firebase中提取一个保存为字符串的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*/)
您可以unixTimestamp使用将日期转换为日期Date(timeIntervalSince1970:)。
unixTimestamp
Date(timeIntervalSince1970:)
let unixTimestamp = 1480134638.0 let date = Date(timeIntervalSince1970: unixTimestamp)
如果要以特定格式在字符串中显示日期,则可以使用DateFormatter这种方式。
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)