'How to add or minus 1 month from current date?

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:

enter image description here



Solution 1:[1]

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)
  • To Add date pass prospective value
  • To Subtract pass negative value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 budiDino