- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想将 doesRelativeDateFormatting
与 Swift 一起使用,以便在我的应用程序上显示日期时获得更多人类可读的日期,例如“今天”或“明天”。但是,在显示非相对日期时,我想显示自定义样式,例如“Wed, Feb 10 '18”。
到目前为止,我可以将预定义的 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())!))
输出:
Today at 11:01:16 AM
Tomorrow at 11:01:16 AM
Tue, Feb 20, 18
如果您需要格式化大量日期,您需要修改此代码,以便它一次创建所有格式化程序,然后在此方法中重用它们。
关于swift - doesRelativeDateFormatting 自定义样式 - 这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772646/
我想将 doesRelativeDateFormatting 与 Swift 一起使用,以便在我的应用程序上显示日期时获得更多人类可读的日期,例如“今天”或“明天”。但是,在显示非相对日期时,我想显示
在 macOS 10.13.3 上使用 NSDateFormatter,当将 doesRelativeDateFormatting 设置为 YES 时,我得到的值不正确。我发现在格式化程序上使用自定义
在 NSDateFormatter 文档中, If a date formatter uses relative date formatting, where possible it replaces
我有许多日期,我试图使用相对日期来表示,例如“今天、昨天、1 周前、1 个月前”等... 这是我使用的 Swift 代码: let dateFormatter = NSDateFormatter()
我是一名优秀的程序员,十分优秀!