您好我试图根据我的后端响应限制特定时间段内的日期选择器值。我推荐很多链接,但没有什么可以帮助我,这是我的代码。
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(时间)是今天下午2点,最大日期(时间)是今天下午11点59分。我不知道我在哪里做错了,有人可以帮助我触发这个......? 在此先感谢....!
答案 0 :(得分:0)
尝试根据时区差异调整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))