UIDatePicker of type "Date & Time" only returns Date and not Time

182 views Asked by At

I'm developing an iOS app which uses a UIDatePicker. The mode is "Date and Time" so the user can pick a date and time from the same picker. You can actually see Day,Time,Hour,Min,AM/PM in the picker.

The problem is, when I try to extract the time AND date (both important), I only get the date printed out even though it's a "Date AND Time" picker (according the Xcode and what I see during runtime).

Here is the code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle

var date = dateFormatter.stringFromDate(sender.date)

println(date)

dateTimeLabel.text = date
dateTimeLabel.textColor = UIColor.blackColor()

It's identical to other examples I see online but I just don't understand why they get Time and Date and I only get the Date. I need the time as well!

The NSDateFormatterStyle.ShortStyle will return something like "6/20/2015, 3:45 PM" but it only returns "6/20/2015" when I print it to the console or the app.

If this is the case, is there a way I can just extract the time then since I already have the date? Honestly, from the other examples I've seen, they get both. I don't know why I only get the date.

Any help would be greatly appreciated!

1

There are 1 answers

0
Martin R On BEST ANSWER

You have to set timeStyle as well, e.g.

dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle

otherwise you'll get only the "date" part.