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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.