gpt4 book ai didi

swift - 在 DatePicker-swift 中限制小时和分钟?

转载 作者:行者123 更新时间:2023-12-04 13:11:57 33 4
gpt4 key购买 nike

大家好,我正在尝试创建一个时间选择器,其中时间仅从(下午 2 点 - 晚上 9 点)开始,分钟增加 30 this is the picture of timePicker that i want to create这是我的代码

func creatTimePicker() {
timePicker.datePickerMode = .time
timePicker.minuteInterval = 30
let timeformatter = DateFormatter()
timeformatter.dateFormat = "HH:mm"

let min = timeformatter.date(from: "5:00")
let max = timeformatter.date(from: "9:00")
timePicker.minimumDate = min
timePicker.maximumDate = max
self.contentView.addSubview(timePicker)
}

问题是小时从 1-12 开始,分钟从 00-59 开始,这是什么问题?谢谢

最佳答案

问题是您还需要设置日期选择器的日期属性以匹配最小日期。您还需要将日期格式化程序的默认日期设置为今天,并且在解析日期字符串时间时不要忘记将语言环境设置为“en_US_POSIX”:

extension Formatter {
static let time: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = .init(identifier: "em_US_POSIX")
formatter.dateFormat = "HH:mm"
return formatter
}()
}

let timePicker = UIDatePicker()
func creatTimePicker() {
Formatter.time.defaultDate = Calendar.current.startOfDay(for: Date())
let minimumDate = Formatter.time.date(from: "14:00")!
let maximumDate = Formatter.time.date(from: "21:00")!
timePicker.date = minimumDate
timePicker.datePickerMode = .time
timePicker.minuteInterval = 30
timePicker.minimumDate = minimumDate
timePicker.maximumDate = maximumDate
self.contentView.addSubview(timePicker)
}

关于swift - 在 DatePicker-swift 中限制小时和分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64220483/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com