UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Problem with dates

Forums > SwiftUI

Hello guys, In my app, after selecting two dates, I'm trying to calculate the days between the two dates and the remaining days before the second date. The problem is I get different output based on the platform. For example: If firstDate is May 31, 2022 and secondDate is June 30, 2022

  • On iOS simulator and real devices: The value of remainingDays is 29 and the value of totalDays is 29.
  • On macOS: The value of remainingDays is 29 and the value of totalDays is 30.
  • Why totalDays have different value based on the platform? Thank you!

struct CalendarExample: View {
    @State private var firstDate: Date = Date()
    @State private var secondDate: Date = Date()

    var remainingDays: String {
        String(difference(Date(), and: secondDate))
    }

    var totalDays: String {
        String(difference(firstDate, and: secondDate))
    }

    var body: some View {
        List {
            Section {
                DatePicker("From", selection: $firstDate, in: ...Date(), displayedComponents: .date)
                DatePicker("To", selection: $secondDate, in: firstDate... , displayedComponents: .date)
            }
            Section {
                Text(remainingDays + " remaining")
                Text(totalDays + " total")
            }
        }
    }

    func difference(_ from: Date, and to: Date) -> Int {
        let numberOfDays = Calendar.current.dateComponents([.day], from: from, to: to)

        return numberOfDays.day!
    }
}

2      

You remainingDays variable has Date() as one parameter and not your chosen date.

2      

Is correct because on remainingDays I'm trying to store the difference between today and the second date.

2      

Check the locale of the simulator, it may not be the locale you are actually living in.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.