fra*_*sto 1 date nsdateformatter swift
我想doesRelativeDateFormatting与Swift 一起使用,以便在我的应用上显示日期时获得更多人类可读的日期,例如“今天”或“明天”。但是,当显示非相对日期时,我想显示一种自定义样式,例如“ 18年2月10日星期三”。
到目前为止,我可以将预定义的dateStyle对象之一与DateFormatter对象一起使用,例如.short或.medium,但是这些对象都不显示工作日和月份的缩写。当从字符串使用自定义格式时,例如“ EEE,MMM d yy”,我会丢失相对日期。
这是一种同时使用它们并在存在时显示相对日期,并为所有其他日期显示自定义日期的方法吗?
当不使用相对格式时,没有直接的方法来获取相对格式和自定义格式。最多可以指定样式,但不能指定格式。
一种解决方案是使用使用三个日期格式化程序的辅助方法。一种使用具有所需样式的相对格式,一种不是相对但使用相同样式的格式,另一种将自定义格式用于非相对日期。
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())!))
Run Code Online (Sandbox Code Playgroud)
输出:
今天上午11:01:16
明天上午11:01:16
2月20日,星期二
如果需要格式化很多日期,则需要修改此代码,以便它一次创建所有格式化程序,然后在此方法中重复使用它们。
| 归档时间: |
|
| 查看次数: |
516 次 |
| 最近记录: |