LAST CHANCE: 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.

2      

Hi, you could do this:

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

2      

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

Thank you in any case. Works perfect

2      

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()
    }
}

2      

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

2      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.