我想以可读的格式显示一周的开始和结束日期。使用
MMMM d
作为日期格式库。例如:
- March 7 - 13
- February 28 - March 6
- 7-13 de marzo
所以如果一周的开始和结束是在同一个月,我只想提到一次月份。我希望这在不同的地方是准确的。例如,在西班牙语和白俄罗斯语中,day位于月份之前,而在西班牙语中,在月份名称之前会添加“de”。
我在用
DateFormatter.dateFormat(
fromTemplate: "MMMM d",
options: 0,
locale: Locale(identifier: Bundle.main.preferredLocalizations.first
获取正确的格式,然后尝试解析它,并用两个数字替换日期,以表示周完全属于同一个月。我意识到我的代码有点粗糙,可能不能保证在所有可能的地方都能工作。但我不知道有没有更简单/更好的方法。
以下是我目前掌握的情况:
func weekDateTitle(firstDay: Date, lastDay: Date) -> String {
let dateTemplate = DateFormatter.dateFormat(
fromTemplate: "MMMM d",
options: 0,
locale: Locale(identifier: Bundle.main.preferredLocalizations.first ?? "en"))
let formatter = DateFormatter()
// If the week ends on the same month as it begins, we use short label format,
// like "Month X - Y"
if firstDay.isSameMonth(as: lastDay) {
formatter.dateFormat = "MMMM"
let month = formatter.string(from: firstDay)
formatter.dateFormat = "d"
let days = "\(formatter.string(from: firstDay)) - \(formatter.string(from: lastDay))"
return dateTemplate?
.replacingFirstOccurrence(of: "MMMM", with: month)
.replacingFirstOccurrence(of: "d", with: days)
.replacingOccurrences(of: "'", with: "") ?? ""
} else {
// Not really important
}
}