Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date from date picker in swift

Tags:

ios

swift

I have created an IBOutlet to a date picker.

@IBOutlet weak var logDate: UIDatePicker!

I have also set the mode of this date picker to date.

Is there a way for me to extract the date that the user would input into the date picker?

I tried using print(logdate), however it also gives me the date along with the time. Like this 2015-10-30 07:10:03 +0000

like image 246
Sachin Avatar asked Feb 08 '23 16:02

Sachin


1 Answers

Perhaps you want this:

let components = logDate.calendar.components([.Era, .Year, .Month, .Day],
    fromDate: logDate.date)
print("\(components.era) \(components.year) \(components.month) \(components.day)")

// Output: 1 2015 10 31

Or perhaps you want this:

let formatter = NSDateFormatter()
formatter.calendar = logDate.calendar
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
let dateString = formatter.stringFromDate(logDate.date)
print(dateString)

// Output: Oct 31, 2015

You can try another dateStyle setting, or be more explicit by setting the dateFormat property. The dateFormat syntax can get pretty hairy. Remember to use yyyy, not YYYY, for the year part of your format. But it's MM, not mm for the month part. Example:

formatter.dateFormat = "yyyy-MM-dd"
print(formatter.stringFromDate(logDate.date))

// Output: 2015-10-31
like image 133
rob mayoff Avatar answered Feb 19 '23 06:02

rob mayoff