WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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!
    }
}

   

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

   

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

   

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

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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

Reply to this topic…

You need to create an account or log in to reply.

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.