I need to be able to add or minus 1 month from the current date.
So far I have this code:
import SwiftUI
struct DateView: View {
    static let dateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.setLocalizedDateFormatFromTemplate("yyyy MMMM")
        return formatter
    }()
    var date = Date()
    var body: some View {
        HStack {
            Button(action: {
                print("Button Pushed")
            }) {
                Image(systemName: "chevron.left")
                .padding()
            }
            Spacer()
            Text("\(date, formatter: Self.dateFormat)")
            Spacer()
            Button(action: {
                print("Button Pushed")
            }) {
                Image(systemName: "chevron.right")
                .padding()
            }
        }
        .padding()
        .background(Color.yellow)
    }
}
struct DateView_Previews: PreviewProvider {
    static var previews: some View {
        DateView()
    }
}
I would like to change the date displayed to be +1 month or -1 month depending on which chevron I will tap.
I am new to swift and swiftui and don't know what action I should use. I think it's related to DateComponents, but what should I do about it now? I am stuck. Please help me.
To better visualise what I have and want to do, here is an image of my current result:

Swift 5
Function to add or subtract month from current date.
func addOrSubtractMonth(month: Int) -> Date {
    Calendar.current.date(byAdding: .month, value: month, to: Date())!
}
Now calling the function
// Subtracting
var monthSubtractedDate = addOrSubtractMonth(-7)
// Adding
var monthAddedDate = addOrSubtractMonth(7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With