0

How do I list yesterday's date in SwiftUI? It probably is a simple answer but I'm just learning to code and for some reason I can't seem to find the solution anywhere. Is it because it is too easy?

struct DateShown: View {
    let datechoice: Datechoice
    var body: some View {
        Text(currentDate(date: Date()))
            .font(.headline)
            .fontWeight(.bold)
            .foregroundColor(.blue)
    }

    func currentDate(date: Date!) -> String {
        let formatter = DateFormatter()
        formatter.locale = .current
        formatter.dateFormat = "MMMM d, yyyy"
        return date == nil ? "" : formatter.string(from: date)
    }
}
izzyk000
  • 59
  • 6
  • Unrelated to the question but never declare an implicit unwrapped optional as parameter type. If it’s supposed to be optional declare it as regular optional (`?`). But here it should be non-optional. – vadian Feb 26 '20 at 12:17
  • Does this answer your question? [NSDate of yesterday](https://stackoverflow.com/questions/26942123/nsdate-of-yesterday) – vadian Feb 26 '20 at 12:19
  • @vadian thanks for the sharing your knowledge. What do you mean by "never declare an implicit unwrapped optional as parameter type. If it’s supposed to be optional declare it as regular optional (?)"? – izzyk000 Feb 26 '20 at 13:04
  • @vadian yup sort of, but I am trying to make it into an array for past dates. Thanks. – izzyk000 Feb 26 '20 at 13:06
  • Either declare `date: Date?` or `date: Date`. In your case the latter because you want to convert a concrete date. For date math `Calendar` is the best choice. – vadian Feb 26 '20 at 13:07

1 Answers1

0

I would rather use View extensions, though you also need Date formatting so I went the easier way and extended your solution. If the number at line "dayComponent.day" is positive, you go futher in time. I tested under:

  • swift 5
  • xcode 11.3.1
  • iOS 13.3.1 non beta

    func yesterDay() -> String {
        var dayComponent = DateComponents()
        dayComponent.day = -1
        let calendar = Calendar.current
        let nextDay =  calendar.date(byAdding: dayComponent, to: Date())!
        let formatter = DateFormatter()
        formatter.locale = .current
        formatter.dateFormat = "MMMM d, yyyy"
        return formatter.string(from: nextDay). //Output is "March 6, 2020
    }
    

Usage is the same as yours:

Text(yesterDay())
Zahovay
  • 135
  • 9