ios - 如何显示日期“今天,4月14日”?

时间:2017-04-13 09:20:02

标签: ios swift nsdate nsdateformatter

我想提供一些读取日期

Yesterday, 13 April
Today, 14 April
Tomorrow, 15 April
Tuesday, 4 April
Wednesday 5 April

我试过

        let date = Date(timeIntervalSince1970: value)

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

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "d MMMM"
        whenLabel.text = dayFormatter.string(from: date) + ", " + dateFormatter.string(from: date)

如果日期是今天,它的工作正常,但是,对于其他日期,我得到“Apr 5, 2017, 5 April”

我怎样才能解决这个问题?

3 个答案:

答案 0 :(得分:1)

根据日期是否为今天,您需要两种完全不同的格式化程序。 doesRelativeDateFormatting无法帮助您完成复杂的格式设置。

首先检查:

if Calendar.current.isDateInToday(date) {
   // use "Today, " + "d MMMM" pattern
} else {
   // use "EEEE" pattern + "d MMMM" pattern
}

答案 1 :(得分:1)

只是为了好玩,这是一个利用本地化相对日期格式的解决方案。

它使用Calendar的扩展名来确定日期是在昨天,今天还是在明天:

extension Calendar {
    func isDateInYesterdayTodayTomorrow(_ date: Date) -> Bool
    {
        return self.isDateInYesterday(date) || self.isDateInToday(date) || self.isDateInTomorrow(date)
    }
}

func relativeDateString(for date: Date, locale : Locale = Locale.current) -> String
{
    let dayFormatter = DateFormatter()
    dayFormatter.locale = locale
    if Calendar.current.isDateInYesterdayTodayTomorrow(date) {
        dayFormatter.dateStyle = .medium
        dayFormatter.doesRelativeDateFormatting = true
    } else {
        dayFormatter.dateFormat = "EEEE"
    }
    let relativeWeekday = dayFormatter.string(from: date)

    let dateFormatter = DateFormatter()
    dateFormatter.locale = locale
    dateFormatter.dateFormat = "d MMMM"
    return  relativeWeekday + ", " + dateFormatter.string(from: date)
}

答案 2 :(得分:0)

正如Sulthan所说,我刚刚了解了这种代码,

let mydate = Date()//my actual date need to display
let dateFormatter = DateFormatter()
if Calendar.current.isDateInToday(mydate) {
     dateFormatter.dateFormat = "'Today,' d MMMM"
}
else if Calendar.current.isDateInYesterday(mydate) {
      dateFormatter.dateFormat = "'Yesterday,' d MMMM"
}
else if Calendar.current.isDateInTomorrow(mydate) {
      dateFormatter.dateFormat = "'Tomorrow,' d MMMM"
}
else{
     dateFormatter.dateFormat = "EEEE, d MMMM"
 }

如果我们有更好的方法,请更新我。感谢