Nathan McKaskle
Nathan McKaskle

Reputation: 3083

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. 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.

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?

Upvotes: 0

Views: 2537

Answers (1)

rmaddy
rmaddy

Reputation: 318934

Split that last line into:

let date = calendar.dateFromComponents(components)!
datePicker.setDate(date, animated: true)

Then look at the value of date. You'll find it is probably January 1, 2000 at the desired time.

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())

Upvotes: 2

Related Questions