在Unix时间戳上使用DateFormatter [英] Using DateFormatter on a Unix timestamp
问题描述
运行时发生崩溃,它指向 dateFormmater.timezone
。
控制台中的错误是:
I get a crash when running and it points at the dateFormmater.timezone
.
The error in the console is:
无法将类型'Swift.Optional'(0x1192bf4a8)的值强制转换为'NSTimeZone '(0x1192c0270)。
Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).
rowEvents.date
的值是 1480134638.0
我正在尝试从保存为字符串的Firebase中提取Unix时间戳。将其转换为Date并再次将其保存为字符串,以便可以将其发布到单元格标签上。
Im trying to pull out a Unix timestamp from Firebase saved as a string. Convert it to Date and again save it as a string so I can post it on a cell label.
我从StackOverflow获得了此代码。我插入了数据,一切运行良好。我想一切都不好...
I got this code from StackOverflow. I plugged in my data and everything is all good until I run it. I guess everything is not all good...
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*/)
推荐答案
您可以使用 Date(timeIntervalSince1970:)
将 unixTimestamp
转换为日期。
You can convert unixTimestamp
to date using Date(timeIntervalSince1970:)
.
let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)
如果要以特定格式在字符串中显示日期,则可以使用 DateFormatter
。
If you want to display date in string with specific formate than you can use DateFormatter
like this way.
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)
这篇关于在Unix时间戳上使用DateFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!