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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.