NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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:, displayedComponents: .date)

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


Hi, you could do this:

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


@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 = DateComponents(day: day), to: self) else {
          fatalError("Unable to get start date from date")
      return date


struct ContentView: View {
    @State private var datePicked =

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

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

        return startComponents)! ... endComponents)!

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


@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 Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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.