Home > Mobile >  Combine Date in swiftui to obtain only one Date
Combine Date in swiftui to obtain only one Date

Time:02-22

Hello I have two date picker one only for date and another for hour and minute


if(showStartDatePicker) {
                    DatePicker("Seleziona data", selection: $selectedStartDate,/* in: startingDate...endingDate,*/ displayedComponents: [.date])
                        .datePickerStyle(.graphical)
                    
                } else if(showStartTimePicker) {
                    DatePicker("Select a date", selection: $selectedStartTime, displayedComponents: [.hourAndMinute])
                        .datePickerStyle(.wheel)
                }

I need to obtain a single date that is the merge of the two date picker

So how can I do?

CodePudding user response:

Just share the variable instead of having 2

struct DoubleDatePickerView: View {
    @State var showStartDatePicker: Bool = false
    @State var selectedStartDate: Date = Date()
    var body: some View {
        VStack{
            Text(selectedStartDate.description)
            if(showStartDatePicker) {
                DatePicker("Seleziona data", selection: $selectedStartDate,/* in: startingDate...endingDate,*/ displayedComponents: [.date])
                    .datePickerStyle(.graphical)
                Button("show time picker", action: {
                    showStartDatePicker.toggle()
                })
            } else  {
                DatePicker("Select a date", selection: $selectedStartDate, displayedComponents: [.hourAndMinute])
                    .datePickerStyle(.wheel)
                Button("show date picker", action: {
                    showStartDatePicker.toggle()
                })
            }
        }
        
    }
}

The other option is to combine the desired components from each variable

var combined: Date{
    let timeComponents: DateComponents = Calendar.current.dateComponents([.hour,.minute,.second,.timeZone], from: selectedStartTime)
    let dateComponents: DateComponents = Calendar.current.dateComponents([.year,.month,.day], from: selectedStartDate)
    let combined: DateComponents = .init(calendar: .current, timeZone: timeComponents.timeZone, year: dateComponents.year, month: dateComponents.month, day: dateComponents.day, hour: timeComponents.hour, minute: timeComponents.minute, second: timeComponents.second)
    return Calendar.current.date(from: combined) ?? Date()
}
  • Related