具有自定义样式的doRelativeDateFormatting - 是否可以?

时间:2018-02-13 17:44:16

标签: swift date nsdateformatter

我想在Swift中使用doesRelativeDateFormatting以获得更易读的日期,例如"今天"或"明天"在我的应用程序上显示日期时。但是,在显示非相对日期时,我想显示一个自定义样式,例如" Wed,Feb 10'"。

到目前为止,我可以使用预定义dateStyle中的一个与我的DateFormatter对象,例如.short.medium,但这些都没有显示工作日和工作日的缩写这个月。当使用字符串中的自定义格式时,例如" EEE,MMM d yy",我会丢失相对日期。

这是一种既可以使用它们又可以显示相对日期的方法,以及所有其他日期的自定义日期?

1 个答案:

答案 0 :(得分:4)

当不使用相对格式时,没有直接的方法来获得相对格式和自定义格式。最多可以指定样式,但不能指定格式。

一种解决方案是使用一种使用三种日期格式化程序的辅助方法。一个使用具有所需样式的相对格式,一个不是相对格式但使用相同样式的格式,另一个使用自定义格式作为非相对日期。

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
  2月20日星期二,星期二

如果您需要格式化大量日期,则需要修改此代码,以便创建所有格式化程序一次,然后在此方法中重复使用它们。