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

SOLVED: DatePicker how to make it so I can choose only the last 3 days?

Forums > 100 Days of SwiftUI

DatePicker("Please enter a time", selection: $dateOfEntry, in: ...Date.now, displayedComponents: .date)
                  .labelsHidden()

This code allows me to choose only the past dates but i want to be able to choose last 3 days only. Like Date.now - 3 days until Date.now.

   

Hi, you could do this:

DatePicker("Please enter a time", selection: $dateOfEntry, in: Date(timeIntervalSinceNow: -259200)...Date.now, displayedComponents: .date)
                          .labelsHidden()

   

@Hectorcrdna if I understand correctly you took 3 days(72 hours) and converted it to seconds?

Thank you in any case. Works perfect

   

I have being working with Date recently. And did this

extension Date {
  public func add(day: Int) -> Date {
      let calendar = Calendar.current
      guard let date = calendar.date(byAdding: DateComponents(day: day), to: self) else {
          fatalError("Unable to get start date from date")
      }
      return date
    }
}

then

struct ContentView: View {
    @State private var datePicked = Date.now

    var dateRange: ClosedRange<Date> {
        let calendar = Calendar.current

        let startComponents = calendar.dateComponents([.day, .month, .year], from: Date.now.add(week: -5))
        let endComponents = calendar.dateComponents([.day, .month, .year], from: Date.now)

        return calendar.date(from: startComponents)! ... calendar.date(from: endComponents)!
    }

    var body: some View {
        DatePicker("Please enter a day", selection: $datePicked, in: dateRange, displayedComponents: .date)
            .labelsHidden()
    }
}

   

@TheFuentes5551, Yes, the Date(timeIntervalSinceNow:) takes it's input in seconds so to go backwards you would subtract the 3 days in seconds.

   

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

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.