【问题标题】:How to display Yesterday, Today, and Tomorrow with DateFormatter如何使用 DateFormatter 显示昨天、今天和明天
【发布时间】:2020-08-31 01:39:43
【问题描述】:

目前,我一直在尝试不同的方法来实现这一壮举。 我在此处对其进行格式化的方式会生成当前日期 8 月 30 日下午 6:28

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 并更新日期时。而不是“8 月 29 日,下午 6:50”出现,我希望字符串是“昨天,下午 6:50”。所有超过昨天和明天的日期都将显示为“MMM d, h:mm a”

【问题讨论】:

  • 我的猜测是修改时间变量,可能分别减去一天或加一。以this 为例
  • 我添加了一个编辑来阐明我的意图。我的道歉

标签: swiftui dateformatter


【解决方案1】:

你需要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
}

【讨论】:

  • 当昨天、今天、明天都超出时,剩余格式为 MM dd, yyyy at h:mm a。如何保留 MMM d, h:mm 格式?
【解决方案2】:

建立在@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)
  }
  
  }
  

This is also something that helped

【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2018-07-20
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多