Calculate difference between two dates and display only the integer values

Hi Team, I have been trying to display the difference between two dates in integer numbers only. This code works in SwiftUI playground. But in the SwiftUI ContentView it gives me an error. I have copied both sets of code below. Any suggestions?

//Swift Playground Code starts here: let theFirstDate = Date(timeIntervalSince1970: 5) let theSecondDate = Date() let theComponents = Calendar.current.dateComponents([.month], from: theFirstDate, to: theSecondDate)

let theNumberOfMonth = theComponents.month

let Months = theNumberOfMonth

//Swift Playground Code ends here // This code works perfectly // Displays the result as "Dec 31, 1969 at 6:00 PM" "Jul 15, 2022 at 6:05 PM" month: 630 isLeapMonth: false  630 630

I am looking to display the number 630 in the SwiftUI code below,


// SwiftUI Code starts here

import SwiftUI struct ContentView: View {     @State var PurchaseDate = Date.now     @State var Months: Int = 0

// Date picker. Here I select a date     var body: some View {         VStack(alignment: .leading){                 DatePicker("Date of Purchase", selection: $PurchaseDate, in: ...Date(), displayedComponents: .date)

Spacer()

// Here we assign today's date             let date = Date()             let dateDiff = Calendar.current.dateComponents([.month], from: PurchaseDate, to: date)

            let Months = dateDiff.month

// In the next line of code, I want to display months in integer, but I get the error             Text("$(Months)") // On this line display error message is "No exact matches in call to instance method 'appendInterpolation'"

        Spacer()
    }

    }

}

Accepted Answer

Please use code formatter when you paste code:

struct ContentView: View {
    @State var PurchaseDate = Date.now
    @State var Months: Int = 0
    // Date picker. Here I select a date
    var body: some View {
        VStack(alignment: .leading){
            DatePicker("Date of Purchase", selection: $PurchaseDate, in: ...Date(), displayedComponents: .date)
            
            Spacer()
            
            // Here we assign today's date
            let date = Date()
            let dateDiff = Calendar.current.dateComponents([.month], from: PurchaseDate, to: date)
            let Months = dateDiff.month
            // In the next line of code, I want to display months in integer, but I get the error
            Text("$(Months)") // On this line display error message is "No exact matches in call to instance method 'appendInterpolation'"
            Spacer()
        }
    }
}

So change with:

            Text("\($Months.wrappedValue)") 

However, what do you want to show: the state var or the new computed Months ?

If so, use

            Text("\(Months)")

Notes:

  • in Swift, var names should start with lowerCase
  • it is a bad idea to recreate a var or const with the same name as another existing (here Months)
  • finally, there seems to be a bug in SwiftUI, where DatePicker doesn't update correctly the state var. See how to solve here:

https://stackoverflow.com/questions/61616452/swiftui-datepicker-does-not-always-update-statedate-variable

Hi Claude31, Thanks for your response. I am new to SwiftUI programming. I am trying to display number of months with just writing few lines of code.

I did use, "Text("The number of months are (Months)")" as you suggested but, I get this error next to that code, "No exact matches in call to instance method 'appendInterpolation'"

I also tried applying the "wrappedValue" as you suggested, Text("($Months.wrappedValue)"), the error goes away, but, in the code one line above that where the Months var is referenced, I get another error as shown below:

      let date = Date()

          let dateDiff = Calendar.current.dateComponents([.month], from: PurchaseDate, to: date)           let Months = dateDiff.month (error message here, "Initialization of immutable value 'Months' was never used; consider replacing with assignment to '_' or removing it") Text("The number of months are ($Months.wrappedValue)") (no error message after applying the wrappedValue)

I will review the link for the stack overflow and see it helps fixing this code. Thanks

Calculate difference between two dates and display only the integer values
 
 
Q