【问题标题】:doesRelativeDateFormatting with a custom style - is it possible?doesRelativeDateFormatting 具有自定义样式 - 可能吗?
【发布时间】:2018-02-13 17:44:16
【问题描述】:
我想将doesRelativeDateFormatting 与 Swift 一起使用,以便在我的应用程序上显示日期时获得更多人类可读的日期,例如“今天”或“明天”。但是,在显示非相对日期时,我想显示自定义样式,例如“Wed, Feb 10 '18”。
到目前为止,我可以将预定义的dateStyle 之一与我的 DateFormatter 对象一起使用,例如 .short 或 .medium,但这些都不会显示工作日和月份的缩写。当使用来自字符串的自定义格式时,例如“EEE,MMM d yy”,我会丢失相对日期。
这是一种同时使用并显示存在的相对日期以及所有其他日期的自定义日期的方法吗?
【问题讨论】:
标签:
swift
date
nsdateformatter
【解决方案1】:
当不使用相对格式时,没有直接的方法来获取相对格式和自定义格式。最多只能指定样式,但不能指定格式。
一种解决方案是使用一种辅助方法,该方法使用三个日期格式化程序。一种使用具有所需样式的相对格式,一种不是相对但使用相同样式的格式,另一种使用您的自定义格式来表示非相对日期。
func formatDate(_ date: Date) -> String {
// Setup the relative formatter
let relDF = DateFormatter()
relDF.doesRelativeDateFormatting = true
relDF.dateStyle = .long
relDF.timeStyle = .medium
// Setup the non-relative formatter
let absDF = DateFormatter()
absDF.dateStyle = .long
absDF.timeStyle = .medium
// Get the result of both formatters
let rel = relDF.string(from: date)
let abs = absDF.string(from: date)
// If the results are the same then it isn't a relative date.
// Use your custom formatter. If different, return the relative result.
if (rel == abs) {
let fullDF = DateFormatter()
fullDF.setLocalizedDateFormatFromTemplate("EEE, MMM d yy")
return fullDF.string(from: date)
} else {
return rel
}
}
print(formatDate(Date()))
print(formatDate(Calendar.current.date(byAdding: .day, value: 1, to: Date())!))
print(formatDate(Calendar.current.date(byAdding: .day, value: 7, to: Date())!))
输出:
今天上午 11:01:16
明天上午 11:01:16
18 年 2 月 20 日,星期二
如果您需要格式化大量日期,您将需要修改此代码,以便一次性创建所有格式化程序,然后在此方法中重复使用它们。