gpt4 book ai didi

ios - 为 DatePicker 设置特定的时间间隔(最小和最大时间)Swift 3

转载 作者:行者123 更新时间:2023-11-30 12:02:12 56 4
gpt4 key购买 nike

您好,我正在尝试根据我的后端响应将我的日期选择器值限制在特定时间段内。我引用了很多链接,但没有任何帮助,这是我的代码。

    datePicker.datePickerMode = .time

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let today = dateFormatter.string(from: Date())

let preprTime = UserDefaults.standard.string(forKey: "PREPARATION_TIME")!
let start = UserDefaults.standard.string(forKey: "START_TIME")!
let end = UserDefaults.standard.string(forKey: "END_TIME")!
//Prints--> preprTime = 30 Mins., start = 08:00:00, end = 23:00:00


dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
let startDt = dateFormatter.date(from: "\(today) \(start) z")
let endDt = dateFormatter.date(from: "\(today) \(end) z")

//Prints--> startDt = 2017-11-02 08:00:00 +0000, endDt = 2017-11-02 23:00:00 +0000

let mins = preprTime.trimmingCharacters(in: CharacterSet(charactersIn: "01234567890").inverted)

let startTime: Date = startDt!.addingTimeInterval(TimeInterval(Int(mins)! * 60))
let endTime: Date = endDt!.addingTimeInterval(-(TimeInterval(Int(mins)! * 60)))

//Prints--> startTime = 2017-11-02 08:30:00 +0000, endTime = 2017-11-02 22:30:00 +0000

datePicker.minimumDate = startTime
datePicker.maximumDate = endTime

//Prints--> datePicker.minimumDate = 2017-11-02 08:30:00 +0000, datePicker.maximumDate = 2017-11-02 22:30:00 +0000

我想我几乎完成了,它打印了正确的值,但是 datePicker 的最小和最大日期设置不正确。这意味着datePicker 的minimumDate(time) 是今天下午2 点,maximumDate(time) 是今天晚上11 点59 分。我不知道我在哪里做错了,有人可以帮助我触发这个......?提前致谢......!

最佳答案

尝试根据时区差异调整您的mimimumDate和maximumDate

区别在于

let gmtDiff = TimeZone.current.secondsFromGMT()

我的时区是+5:30,所以我需要从开始和结束时间中减去它

var startDt = dateFormatter.date(from: "\(today) \(start) z")
startDt = startDt?.addingTimeInterval( -TimeInterval(gmtDiff))
var endDt = dateFormatter.date(from: "\(today) \(end) z")
endDt = endDt?.addingTimeInterval( -TimeInterval(gmtDiff))

关于ios - 为 DatePicker 设置特定的时间间隔(最小和最大时间)Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47076919/

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