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
相关产品推荐
相关产品推荐

