Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

swift - Using DateFormatter on a Unix timestamp

I get a crash when running and it points at the dateFormmater.timezone. The error in the console is:

Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).

the value of rowEvents.date is "1480134638.0"

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.

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              
}

The result came from this code here:

let myTimeStamp = self.datePicker?.date.timeIntervalSince1970

let calendarDate = String(describing: myTimeStamp! /** 1000*/)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can convert unixTimestamp to date using Date(timeIntervalSince1970:).

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...