如何在 Swift 中将旧样式的 DateFormatter 与较新的 FormatStyle API 结合使用。
旧:
let df = DateFormatter()
df.formatString = "ddd MMMM yy"
df.string(from: Date()) // >> 27 May 24
新:
date.formatted(date: .abbreviated, time: .omitted) // > 27 May 24
Date().formatted(/* fixed format in here? */)
注意:我不需要使用
DateFormatter
本身,我只需要格式化的字符串样式。
如果我理解正确的话,你不能直接使用 Date().formatted() 的字符串格式。
它旨在与 FormatStyle API 配合使用,它提供了一种结构化的方法来使用工作日、月份、年份等组件自定义日期和时间格式。
let formattedDate = Date().formatted(
.dateTime.weekday(.abbreviated)
.month(.wide)
.year(.twoDigits)
)
print(formattedDate)
let formattedDate2 = Date().formatted(
.dateTime.weekday(.wide)
.month(.wide)
.day()
.year()
)
print(formattedDate2)
您可以调整组件及其宽度以创建各种不同的字符串格式。
关键点: 您不是直接使用“ddd MMMM yy”之类的字符串格式,而是指定各个组件及其所需的样式。
如果您心中有特定的字符串格式,请尝试将其分解为各个组成部分并使用相应的
FormatStyle
元素。