Converting a Unix timestamp into Date as String? S

2019-01-17 21:01发布

问题:

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*/)

回答1:

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)


回答2:

The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!.

Simply use TimeZone instead of NSTimeZone like
dateFormatter.timeZone = TimeZone.current and your code will work.

You might also remove your / 1000 because 1480134638.0 looks more like seconds than milliseconds (since 1970).



回答3:

Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.

func getDateFromTimeStamp(timeStamp : Double) -> String {

        let date = NSDate(timeIntervalSince1970: timeStamp)

        let dayTimePeriodFormatter = DateFormatter()
        dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a"
     // UnComment below to get only time
    //  dayTimePeriodFormatter.dateFormat = "hh:mm a"  

        let dateString = dayTimePeriodFormatter.string(from: date as Date)
        return dateString
    }


回答4:

This solution is valid for swift 3 -> 4.2 :

you can add an extension on the Double that returns the date formatted:

extension Double {


    // returns the date formatted.    
    var dateFormatted : String? {
        let date = Date(timeIntervalSince1970: self)
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = DateFormatter.Style.none //Set time style
        dateFormatter.dateStyle = DateFormatter.Style.short //Set date style
        return dateFormatter.string(from: date)
     }

    // returns the date formatted according to the format string provided. 
    func dateFormatted(withFormat format : String) -> String{
         let date = Date(timeIntervalSince1970: self)
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = format
         return dateFormatter.string(from: date)
    }

}

example on the above :

let timeStamp = 82749029.0
print(timeStamp. dateFormatted)
//output
//12/11/1994



let timeStamp = 82749029.0
print(timeStamp. dateFormatted(withFormat : "MM-dd-yyyy HH:mm"))
//output
//12-11-1994 13:04