DatePicker

Published by @SoNiceInfo at 6/24/2020


DatePicker is used for select date.

How to useDatePicker

First, Prepare Date variable to input date.
In the DatePicker argument, pass the binding variable as selection and date unit as displayedComponents.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView : View {
    @State var selectedDate = Date()

    var body: some View {
        VStack {
            DatePicker(selection: $selectedDate, displayedComponents: .hourAndMinute) {
                Text("Hour\nMinute")
            }

            DatePicker(selection: $selectedDate, displayedComponents: .date) {
                Text("Date")
            }

            DatePicker(selection: $selectedDate, displayedComponents: [.date, .hourAndMinute]) {
                Text("Both")
            }

            Text(selectedDate.description)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
How to use date picker.

Hide DatePicker label

DatePicker label appears at weird position.
Use .labelsHidden() to hide it.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView : View {
    @State var selectedDate = Date()

    var body: some View {
        VStack {
            DatePicker(selection: $selectedDate, displayedComponents: .hourAndMinute) {
                Text("Hour\nMinute")
            }.labelsHidden()

            DatePicker(selection: $selectedDate, displayedComponents: .date) {
                Text("Date")
            }.labelsHidden()

            DatePicker(selection: $selectedDate, displayedComponents: [.date, .hourAndMinute]) {
                Text("Both")
            }.labelsHidden()

            Text(selectedDate.description)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
how to hide datepicker label.

Arrange date format

DateFormatter can change date format.
You can define You can set the availability of dates and times, the date output method, and the time zone.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView : View {
    @State var selectedDate = Date()
    @Environment(\.timeZone) var timeZone

    var dateFormat: DateFormatter {
        let dformat = DateFormatter()
        dformat.dateStyle = .medium
        dformat.timeStyle = .medium
        dformat.dateFormat = "yyyy-MM-dd HH:mm"
        dformat.timeZone  = timeZone
        return dformat
    }

    var body: some View {
        VStack {
            DatePicker(selection: $selectedDate, displayedComponents: .hourAndMinute) {
                Text("Hour\nMinute")
            }.labelsHidden()

            DatePicker(selection: $selectedDate, displayedComponents: .date) {
                Text("Date")
            }.labelsHidden()

            DatePicker(selection: $selectedDate, displayedComponents: [.date, .hourAndMinute]) {
                Text("Both")
            }.labelsHidden()

            Text("Original: \(selectedDate.description)")
            Text("DateFormat: \(selectedDate, formatter: dateFormat)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
dateformatterを使って形式を変更した結果

Create DatePicker with minute interval

You can create DatePicker with minute interval by using UIDatePicker of UIKit.
The point here is picker.minuteInterval = MINUTES. Please check Display Map to use UIKit module in SwiftUI View.

//
//  ContentView.swift
//

import SwiftUI

struct ContentView: View {
    @State var selectedDate = Date()
    @Environment(\.timeZone) var timeZone

    var dateFormat: DateFormatter {
        let dformat = DateFormatter()
        dformat.dateStyle = .medium
        dformat.timeStyle = .medium
        dformat.dateFormat = "yyyy-MM-dd HH:mm"
        dformat.timeZone  = timeZone
        return dformat
    }

    var body: some View {
        VStack {
            MyDatePicker(selection: $selectedDate, minuteInterval: 5, displayedComponents: .hourAndMinute)
            MyDatePicker(selection: $selectedDate, minuteInterval: 30, displayedComponents: [.hourAndMinute, .date])

            Text("Original: \(selectedDate.description)")
            Text("DateFormat: \(selectedDate, formatter: dateFormat)")
        }
    }

}

struct MyDatePicker: UIViewRepresentable {

    @Binding var selection: Date
    let minuteInterval: Int
    let displayedComponents: DatePickerComponents

    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    func makeUIView(context: UIViewRepresentableContext<MyDatePicker>) -> UIDatePicker {
        let picker = UIDatePicker()
        // listen to changes coming from the date picker, and use them to update the state variable
        picker.addTarget(context.coordinator, action: #selector(Coordinator.dateChanged), for: .valueChanged)
        picker.minuteInterval = minuteInterval
        return picker
    }

    func updateUIView(_ picker: UIDatePicker, context: UIViewRepresentableContext<MyDatePicker>) {
        picker.date = selection

        switch displayedComponents {
        case .hourAndMinute:
            picker.datePickerMode = .time
        case [.hourAndMinute, .date]:
            picker.datePickerMode = .dateAndTime
        default:
            break
        }
    }

    class Coordinator {
        let datePicker: MyDatePicker
        init(_ datePicker: MyDatePicker) {
            self.datePicker = datePicker
        }

        @objc func dateChanged(_ sender: UIDatePicker) {
            datePicker.selection = sender.date
        }
    }
}
数分間隔のDatePickerを作成する

References

DatePicker - SwiftUI | Apple Developer Documentation
DateFormatterの使い方まとめ - Qiita
swift - DatePicker using Time-Interval in SwiftUI - Stack Overflow

    I released iOS App!

    ToDo App

    Visualize Activity, Data sharing with iCloud, Dark mode supported.

    リリースしたToDoアプリのスクリーンショット

    IP Address bookmark.

    Check and bookamrk IP address of all interfaces with geolocation.

    リリースしたIPアドレス保存アプリのスクリーンショット