本文介绍了Swift的日期格式TODAY TOMORROW YESTERDAY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将日期显示为 6月13日星期六.

如果日期是当前日期,则应显示 Today (今天),就像 Tomorrow (明天),昨天一样.

If the date is current day it should display Today like that Tomorrow, Yesterday.

我两个都做不到

guard let date = Date(fromString: "16 September 2020",
                      format: "dd MMMM yyyy") else { return nil }

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.doesRelativeDateFormatting = true

        header.titleLabel.text = dateFormatter.string(from: date)

对于上述代码,我可以将日期显示为今天 明天 昨天,但其他日期未显示 6月13日星期六.我试图将日期格式 dateFormatter.dateFormat ="EEEE,MMM d" 应用于相同的 dateFormatter ,但未返回任何内容.

For the above code I can show date as Today Tomorrow Yesterday but other dates are not showing Saturday June 13. I tried to apply date format dateFormatter.dateFormat = "EEEE, MMM d" for the same dateFormatter it returned nothing.

推荐答案

设置 doesRelativeDateFormatting = true 并尝试同时应用自定义格式时,DateFormatter表现不佳.因此,最简单的解决方案是使用 Style Locale

The DateFormatter doesn't behave well when setting doesRelativeDateFormatting = true and trying to apply a custom format at the same time. So the easiest solution is to use the format given by a Style and a Locale

let relativeDateFormatter = DateFormatter()
relativeDateFormatter.timeStyle = .none
relativeDateFormatter.dateStyle = .medium
relativeDateFormatter.locale = Locale(identifier: "en_GB")
relativeDateFormatter.doesRelativeDateFormatting = true

示例

let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd"

let dates = ["2020-09-01", "2020-09-15", "2020-09-16", "2020-09-30"].compactMap { inputFormatter.date(from: $0)}

for date in dates {
    print(relativeDateFormatter.string(from: date))
}

现在,如果您要应用自定义格式,则在使用相同的DateFormatter实例时,我还没有找到解决方案,因此我们需要为该自定义格式创建一个新的格式,并将其与选中项一起使用,以便我们应用自定义格式仅当不是今天等格式时格式化

Now if you want to apply a custom format I have not found a solution for this when using the same DateFormatter instance so we need to create a new one for the custom format and use it together with a check so we apply the custom format only when it is not Today etc

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM dd"

for date in dates {
    let string = relativeDateFormatter.string(from: date)
    if let _ = string.rangeOfCharacter(from: .decimalDigits) {
         print(dateFormatter.string(from: date))
    } else {
        print(string)
    }
}

这篇关于Swift的日期格式TODAY TOMORROW YESTERDAY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:49