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

Swift中如何将日期格式化为月份与年份?

修改方案

要实现「月份全称, 年份」的格式(如「September, 2022」),只需要修改代码中转换日期用的DateFormatter的格式字符串即可:

修改后的完整代码

func getDayMonDateFormat() -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.locale = Locale.current
    guard let oldDate = dateFormatter.date(from: self) else { return "" }
    let convertDateFormatter = DateFormatter()
    // 替换为目标格式字符串
    convertDateFormatter.dateFormat = "MMMM, yyyy"
    // 可选:如果需要强制固定语言(比如始终英文),可以指定locale
    // convertDateFormatter.locale = Locale(identifier: "en_US_POSIX")
    return convertDateFormatter.string(from: oldDate)
}

关键修改点

  • 将convertDateFormatter.dateFormat的值从原来的"EEEE, dd MMM"改为"MMMM, yyyy":
    • MMMM代表月份的完整名称(如September、December)
    • yyyy代表4位数的年份
  • 如果需要输出其他语言的月份名称(比如中文「九月, 2022」),只需给convertDateFormatter指定对应locale即可,例如:
    convertDateFormatter.locale = Locale(identifier: "zh_CN")
    

内容的提问来源于stack exchange,提问作者Ezgi Özkan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:05:22