You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何将Date类型timestamp格式化为May 10, 2018 10:00 PM样式?

解决Swift中日期格式化的问题

嗨,我来帮你搞定这个日期显示的问题!你需要在ModelTableViewCell的update(with:)方法里替换掉直接转字符串的代码,用DateFormatter来生成你想要的格式。具体步骤如下:

1. 添加静态的日期格式化器

首先在ModelTableViewCell类里定义一个静态的DateFormatter实例——这么做是因为创建DateFormatter比较耗性能,复用同一个实例能提升效率:

class ModelTableViewCell: UITableViewCell {
    @IBOutlet weak var firstNameLabel: UILabel!
    @IBOutlet weak var lastNameLabel: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    
    // 静态日期格式化器,只初始化一次
    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        // 设置目标格式:May 10, 2018 10:00 PM
        formatter.dateFormat = "MMM dd, yyyy hh:mm a"
        // 可选:如果需要转换成本地时区显示,取消下面注释
        // formatter.timeZone = TimeZone.current
        return formatter
    }()
    
    // ... 其他代码
}

2. 在update方法中使用格式化器

把原来直接将Date转成字符串的代码,替换成用格式化器处理后的结果:

func update(with name: Model) {
    firstNameLabel.text = name.firstName
    lastNameLabel.text = name.lastName
    // 这里就是你要修改的核心位置!
    dateLabel.text = ModelTableViewCell.dateFormatter.string(from: name.timestamp)
}

格式参数说明

  • MMM:月份的英文缩写(比如May、Jun)
  • dd:两位数的日期(01-31)
  • yyyy:四位年份(2018、2024)
  • hh:12小时制的小时(01-12)
  • mm:两位数的分钟(00-59)
  • a:自动显示AM/PM标识(上午/下午)

这样修改后,你的dateLabel就会完美显示成May 10, 2018 10:00 PM这种样式啦!

内容的提问来源于stack exchange,提问作者ivansunder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:25:17