Swift 如何编码“let timestamp:Date”以获取2018年5月10日10:00 PM
在我的日期标签中,我得到以下结果2018-05-09 02:21:23+0000。 我需要在代码的哪个位置执行“日期格式化”,以获得2018年5月10日晚上10:00。 多谢各位Swift 如何编码“let timestamp:Date”以获取2018年5月10日10:00 PM,swift,date,date-formatting,Swift,Date,Date Formatting,在我的日期标签中,我得到以下结果2018-05-09 02:21:23+0000。 我需要在代码的哪个位置执行“日期格式化”,以获得2018年5月10日晚上10:00。 多谢各位 struct Model { let firstName: String let lastName: String let timestamp: Date static func loadSampleData() -> [Model] { return [
struct Model {
let firstName: String
let lastName: String
let timestamp: Date
static func loadSampleData() -> [Model] {
return [
Model(firstName: "john", lastName: "doe", timestamp: Date()),
Model(firstName: "alex", lastName: "doe", timestamp: Date()),
Model(firstName: "lisa", lastName: "doe", timestamp: Date())
]
}
}
class ModelTableViewCell: UITableViewCell {
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
func update(with name: Model) {
firstNameLabel.text = name.firstName
lastNameLabel.text = name.lastName
dateLabel.text = "\(name.timestamp)"
}
}
在更新方法中使用日期格式化程序,而不是使用字符串插值
func update(with name: Model) {
firstNameLabel.text = name.firstName
lastNameLabel.text = name.lastName
let fmt = DateFormatter()
fmt.dateStyle = .medium
fmt.timeStyle = .medium
dateLabel.text = fmt.string(from: name.timestamp)
}
设置样式以满足您的需要。日期格式化程序是一个非常沉重的对象,因此不要将其设置为本地对象,并尝试在整个应用程序中重用该对象。为此,您可以对DateFormatter进行扩展,并在其中为该格式化程序创建一个静态属性。定义该扩展中的所有格式化程序。要在应用程序中的任何地方使用它,请延长日期并使用它
extension DateFormatter {
static let shortDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd,yyyy hh:mm a"
return formatter
}()
}
extension Date {
/// Prints a string representation for the date with the given formatter
func string(with format: DateFormatter) -> String {
return format.string(from: self)
}
/// Creates an `Date` from the given string and formatter. Nil if the string couldn't be parsed
init?(string: String?, formatter: DateFormatter) {
guard let date = formatter.date(from: string ?? "") else { return nil }
self.init(timeIntervalSince1970: date.timeIntervalSince1970)
}
}
在updatewith name:Model方法中使用它,如下所示:
let strDate = name.timestamp.string(with: .shortDate)
现在在标签中传递strDate。
如果要转换日期中的字符串,请使用stringwith format:DateFormatter方法 你真的应该避免使用dateFormat。使用dateStyle和timeStyle将提供与用户期望看到的格式相匹配的输出。如果还有其他原因避免使用dateFormat,那就差不多了。您不应该使用dateFormat向用户显示日期。对不起。我有搜索功能,但我没有找到任何不使用dateFormat的理由。我告诉过你原因-这是糟糕的用户体验。根据用户居住的位置,他们希望看到以某种常见方式格式化的日期和时间。当您使用dateFormatter时,您强制用户以一种意外且令人困惑的格式及时查看日期。