'How to give DatePicker a minute interval in SwiftUI

does anyone know how to give the minutes DatePicker an interval? I am trying to only display multiples of 15 (0, 15, 30, 45). Is this only yet possible by interfacing with UIKit?

I believe it's not using the in: ...Date() part, at least I couldn't think of a solution. Here is my snippet:

DatePicker(
                "",
                selection: $selectedDate,
                /*in: ...Date(),*/
                displayedComponents: .hourAndMinute
            )

Thanks so much!



Solution 1:[1]

The solution is to configure using UIDatePicker.appearance before SwiftUI DatePicker is created.

Tested with Xcode 13.3 / iOS 15.4

demo

Main part is:

UIDatePicker.appearance().minuteInterval = 15

Complete code in here

Solution 2:[2]

What about using two pickers, one for hour and one for minute, and then converting to Date() afterwards? It's not pretty but this gets part of the way there:

struct ContentView: View {
    @State private var hour = 1
    @State private var minute = 0

    let minutes = [0, 15, 30, 45]

    var body: some View {
        GeometryReader { geometry in
            HStack {
                Picker("Hour", selection: self.$hour) {
                    ForEach(1...12, id: \.self) {
                        Text("\($0)")
                    }
                }
                .labelIsHidden()
                .frame(maxWidth: geometry.size.width / 4)
                .clipped()

                Picker("Minutes", selection: self.$minute) {
                    ForEach(self.minutes, id: \.self) { minute in
                        Text(minute == 0 ? " : 0\(minute)" : " : \(minute)")
                    }
                }
                .labelIsHidden()
                .frame(maxWidth: geometry.size.width / 4)
                .clipped()

            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asperi
Solution 2