我想从两个日期创建一个日期字符串,格式如下:
"Apr 21 - Sep 17, 2018" - US
"21 Apr - 17 Sep, 2018" - Elsewhere
同时遵守本地日期格式(美国为 MMM dd,欧洲为 dd MMM 等)。
如何让 DateFormatter 为我提供默认样式但没有年份?
let startDateFormatter = DateFormatter()
// How to keep medium style but without year?
// this is the US style,
// I want locale-independent style to match the other date formatter
startDateFormatter.dateFormat = "MMM dd"
let endDateFormatter = DateFormatter()
endDateFormatter.dateStyle = .medium
endDateFormatter.timeStyle = .none
let startDateText = startDateFormatter.string(from: startDate)
let endDateText = endDateFormatter.string(from: endDate)
最佳答案
使用DateIntervalFormatter
。这旨在为您提供一个正确本地化的字符串,表示两个日期之间的日期间隔。
以下是您的两个日期的示例:
// Test code for the two dates
let firstDate = Calendar.current.date(from: DateComponents(year: 2018, month: 4, day: 21))!
let lastDate = Calendar.current.date(from: DateComponents(year: 2018, month: 9, day: 17))!
let dif = DateIntervalFormatter()
dif.timeStyle = .none
dif.dateStyle = .medium
let dateInt = dif.string(from: firstDate, to: lastDate)
结果(美国):
Apr 21 – Sep 17, 2018
结果(英国):
21 Apr – 17 Sep 2018
如果您确实需要将 DateFormatter
与正确本地化的特定 dateFormat
一起使用(例如月份和日期,但没有年份),请使用 setLocalizedDateFormatFromTemplate
.
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("MMMdd")
let result = df.string(from: Date())
这将提供仅包含日期和缩写月份的正确本地化结果。
关于iOS Swift 如何为任何语言环境设置没有年份的 DateFormatter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51267284/