iOS Swift 如何为任何语言环境设置没有年份的 DateFormatter?

标签 ios swift date nsdateformatter dateformatter

我想从两个日期创建一个日期字符串,格式如下:

"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/

相关文章:

ios - 如何将 MBProgressHUD 的位置固定在 UITableView 的中心

ios - 在自动布局环境中移动 UIView

ios - 创建要在选择器 View 中使用的数字数组不起作用

swift - 枚举行为理解(Swift 应用开发介绍 - 第 19 课)

objective-c - 如何从 SQLite3 行中获取日期或日期时间?

ios - SwiftUI 中的动态过滤器(谓词)

ios - 在 swift 4.2 xcode 中隐藏和显示 View

ios - 创建 AVPlayerLayer 会阻止释放 AVPlayer

javascript - 从字符串中提取有效日期

python - 在Python中对数据文件进行排序