Search code examples
iosswiftnsdateformatter

How to format date correctly


How do I format this date so that it is readable. I want it to show for example: "January 7th, 2018 7:30am". I tried to look at other answers but wasn't sure where to add the extension.

    let date = Date(timeIntervalSince1970: request.timestamp / 1000)
    dateCell.textLabel?.text = date.description



class Request {
var key:String
var sender:String
var recipient:String
var name:String
var location:String
var when:String
 var whereStr:String
var message:String
var timestamp:Double
var status:String

init(dict: [String: Any]) {
    self.key       = dict["key"] as? String ?? ""
    self.sender    = dict["sender"] as? String ?? ""
    self.recipient = dict["recipient"] as? String ?? ""
    self.name      = dict["name"] as? String ?? ""
    self.location  = dict["location"] as? String ?? ""
    self.when      = dict["when"] as? String ?? ""
    self.whereStr  = dict["where"] as? String ?? ""
    self.message   = dict["message"] as? String ?? ""
    self.timestamp = dict["timestamp"] as? Double ?? 0.0
    self.status    = dict["status"] as? String ?? ""
}

enter image description here


Solution

  • Try This

     func getCurrentDateTimeFromTimeStamp(timeStapm:String)->String{
        let date = NSDate(timeIntervalSince1970:Double(timeStapm)!/1000)
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM d, yyyy HH:mm a"
        return formatter.string(from: date as Date)
     }
    

    pass timestamp and get as date in string format as per your requirement just pass dateFormat.

    use like this

    dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timeStapm:"pass your timestamp")