如何使用 DateFormatter 显示昨天、今天和明天

How to display Yesterday, Today, and Tomorrow with DateFormatter

目前,我一直在尝试不同的方式来实现这一壮举。 我在这里格式化的方式产生了当前日期 Aug 30, 6:28 PM

import SwiftUI

struct TestDate: View {
var time = Date()

var dateFormatter: DateFormatter {
    let df = DateFormatter()
    df.dateFormat = "MMM d, h:mm a"
    return df
}


var body: some View {
    Text("\(time, formatter: dateFormatter)")
}
}

这正是我想要的。但是,我希望昨天、今天和明天出现,而不是“8 月 30 日”/相对当前日期。如何在 SwiftUI 中做到这一点

编辑:我的意思是当我使用 DatePicker 并更新日期时。而不是出现“Aug 29, 6:50 PM”,我希望字符串是“Yesterday, 6:50 PM”。所有超过昨天和明天的日期将显示为“MMM d, h:mm a”

您需要 doesRelativeDateFormatting(并且不要忘记添加样式),例如:

var dateFormatter: DateFormatter {
    let df = DateFormatter()
    df.dateFormat = "MMM d, h:mm a"

    df.dateStyle = .medium
    df.timeStyle = .short
    df.doesRelativeDateFormatting = true

    return df
}

建立在@Asperi 所说的之上。我实现这一点的方法是编写一个函数来按照我想要的方式格式化。

import SwiftUI

struct TestDate: View {
var time = Date()




var body: some View {
    Text("\(format(date: time))")
}

//this is where the function is I'm sure this could be cleaned up but here it is in its long form.
func format(date: Date) -> String {
      let calendar = Calendar.current
  if calendar.isDateInToday(date){
          let df = DateFormatter()
          df.dateStyle = .short
          df.timeStyle = .short
          df.doesRelativeDateFormatting = true
      return df.string(from: date)
      
      }
else if calendar.isDateInYesterday(date){
      let df = DateFormatter()
          df.dateStyle = .short
          df.timeStyle = .short
          df.doesRelativeDateFormatting = true
      return df.string(from: date)
  }
  else if calendar.isDateInTomorrow(date){
      let df = DateFormatter()
          df.dateStyle = .short
          df.timeStyle = .short
          df.doesRelativeDateFormatting = true
      return df.string(from: date)
      } else {
          let df = DateFormatter()
          df.dateFormat = "MMM d, h:mm a"
      return df.string(from: date)
  }
  
  }