首页 > 解决方案 > 在 SwiftUI 中使用 DatePicker 时如何将时间设置为标准值

问题描述

我的应用程序中有一个日期选择器,它只选择日期,而不是时间。看起来像这样:

DatePicker("Birthday",
          selection: $date,
          displayedComponents: [.date])

日期选择器为您提供了一个可以使用的日期对象。所以,当用户选择日期时,它当然也带有时间、时区等。我的问题是,时间默认设置为当前时间。但是,我需要将其始终设置为午夜。如何提供默认值?

我想到的一个可能的解决方案是使用格式化程序并将日期存储为字符串(而不是日期),但由于我需要稍后对其进行一些处理(例如计算两个日期之间的天数),所以这不会对我来说似乎是最好的方法。

标签: swiftdateswiftui

解决方案


你可以试试这个:

struct ContentView: View {
    @State var date = Date()
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
                .onChange(of: date) { newDate in
                    if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: newDate) {
                        date = midnight
                        
                    }
                }
        }
    }
}

或这个:

struct ContentView: View {
    @State var date = Date()
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
        .onAppear {
            if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) {
                date = midnight
            }
        }
    }
}

或这个:

struct ContentView: View {
    @State var date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
    }
}

推荐阅读