[英]Swift 2.1 DatePicker setDate does not set date to current day and specified time
I am trying to set the minimum date to the current day on the date picker and then for the sake of user experience, set the time to 7pm or 19:00. 我正在尝试将最小日期设置为日期选择器上的当前日期,然后为了用户体验,将时间设置为7pm或19:00。 For some reason it doesn't seem to be working.
由于某种原因,它似乎无法正常工作。 The minimum date setting works but the time doesn't get set.
最小日期设置有效,但未设置时间。 If I remove the minimum date line, the time gets set to 7pm, but strangely, the date gets set to Monday, Jan 1. Which isn't even this year.
如果我删除了最小日期行,则时间设置为晚上7点,但是奇怪的是,日期设置为1月1日,星期一。
Here's my code below: 这是我的代码如下:
datePicker.minimumDate = NSDate()
let calendar:NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: NSDate())
components.hour = 19
components.minute = 00
datePicker.setDate(calendar.dateFromComponents(components)!, animated: true)
What am I doing wrong here? 我在这里做错了什么?
Split that last line into: 将最后一行分成:
let date = calendar.dateFromComponents(components)!
datePicker.setDate(date, animated: true)
Then look at the value of date
. 然后看一下
date
的值。 You'll find it is probably January 1, 2000 at the desired time. 您会发现它可能是在所需时间的2000年1月1日。
Fix this by adding the year, month, and day components to: 通过将年,月和日组成部分添加到以下内容来解决此问题:
let components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: NSDate())
In other words, you need: 换句话说,您需要:
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: NSDate())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.