如何正确格式化日期

时间:2018-02-10 08:59:57

标签: ios swift nsdateformatter

如何格式化此日期以使其可读。我希望它能够显示例如:“2018年1月7日上午7:30”。我试着查看其他答案,但不知道在哪里添加扩展名。

    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

4 个答案:

答案 0 :(得分:0)

您应该使用DateFormatter:

let formatter = DateFormatter()
formatter.format = "MMMM d, yyyy HH:mm a"
let dateString = formatter.string(from: date)

答案 1 :(得分:0)

试试这个

 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)
 }

传递时间戳,并根据您的要求以字符串格式获取日期,只需传递dateFormat。

像这样使用

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

答案 2 :(得分:0)

您可以在应用中的任意位置添加扩展程序,也可以为comlpete应用添加一个(相同名称)扩展程序。看下面

import UIKit

class ViewControllerHellBoy: UIViewController
{
override func viewDidLoad() {
    super.viewDidLoad()


    // Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

       func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     dateCell.textLabel?.text = self.userFriendlyFullDate()
}




}  
extension Date: Dateable {
var  formatter: DateFormatter { return DateFormatter() }

/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
    // Customize a date formatter
    formatter.dateFormat = ""MMMM d, yyyy HH:mm a"" //Use format you want to
    formatter.timeZone = TimeZone(abbreviation: "UTC") . // Time zone you wishes to provide

    return formatter.string(from: self)
}

这就是你可以使用扩展的方法。您还可以创建单独的类并保留所有扩展名。

答案 3 :(得分:0)

使用dateFormatter对象来设置日期的样式

let format = DateFormatter()
    format.format = "MM/dd/yyyy"

//get your date in string like this
let dateInString = format.string(from: date)

// this will give you "10/02/2018"

您可以访问date format examples以查看不同格式以及如何获取这些格式。