Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or minus 1 month from current date?

Tags:

swiftui

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

like image 670
mallow Avatar asked Sep 16 '25 07:09

mallow


1 Answers

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
like image 106
Md. Enamul Haque Avatar answered Sep 18 '25 10:09

Md. Enamul Haque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!