WWDC24 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.


Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.