gpt4 book ai didi

swift - doesRelativeDateFormatting 自定义样式 - 这可能吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:30 25 4
gpt4 key购买 nike

我想将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com