AziCode
AziCode

Reputation: 2692

UIDatePicker Time Issues

I have a problem with my UIDatePicker:

When it first appears on the view as you'll see in the screenshot,

the initial value of the UIDatePicker says Today 3:00 pm, but if I click on the done button the label shows 3:07 ( which is the actual time ). I want the Label to display the same time as the UIDatePicker.

here is my code:

override func viewDidLoad() {
super.viewDidLoad()
   myDatePicker.minuteInterval = 15
}

@IBAction func datePickerAction(sender: AnyObject) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    var strDate = dateFormatter.stringFromDate(myDatePicker.date)
    self.selectedDate.text = strDate
}

enter image description here enter image description here

Upvotes: 3

Views: 558

Answers (1)

Mundi
Mundi

Reputation: 80271

You need to adjust the initial date to the discrete minute amounts at first. I am sure your date picker works just fine once you change the value, right? When you set the date picker to a date (like 3:07) but the date picker is set to show only increments of 15 minutes, it will show 3:00, but the set date is still 3:07.

let allUnits = NSCalendarUnit(rawValue: UInt.max)
let components = NSCalendar.currentCalendar().components(allUnits, fromDate: NSDate())

var minute = components.minute
minute = (minute / 15) * 15
components.minute = minute

let datePickerDate = NSCalendar.currentCalendar().dateFromComponents(components)

This always rounds the minutes downwards (while you might want to round up if the minute % 15 > 7 and then account for rounding up to 60), but you get the idea.

Upvotes: 4

Related Questions