我想以人類可讀的格式顯示一周的開始和結束日期。用作MMMM d日期格式基礎。例如:
- March 7 - 13
- February 28 - March 6
- 7-13 de marzo
因此,如果周開始和結束在同一個月內,我只想提及一次月份。我希望這在不同的語言環境中是準確的。例如,在西班牙語和白俄羅斯語中,天會在月份之前,而在西班牙語中,月份名稱之前會添加“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
}
}
uj5u.com熱心網友回復:
考慮DateIntervalFormatter:
let formatter = DateIntervalFormatter()
formatter.locale = locale
formatter.dateTemplate = "MMMMd"
let string = formatter.string(from: date1, to: date2)
同一個月,這將產生“7 – 13 de marzo”和“3 月 7 – 13 日”。
對于不同的月份,“7 de febrero – 13 de marzo”和“2 月 7 日 – 3 月 13 日”。
這些格式化程式有一些奇怪的邊緣情況(例如,在英語語言環境dateStyle中的作品,但在其他地方沒有)。.long如果上述方法在您的所有目標語言環境中都不能完美運行,我不會感到驚訝,因此您可能需要仔細檢查。但是,根據我的經驗,這些格式化程式可以讓你非常接近。它似乎可以用英語和西班牙語實作您所需要的……
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447534.html
