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
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
You can extract the date inputted by the user in a date field using this code. Note: This solution extracts the input as a string
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle // You can also use Long, Medium and No style.
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var inputDate = dateFormatter.stringFromDate(*datepicker outlet name*.date)
print(inputDate)
Used a section of code from: http://www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift
Swift 5
It's more simple than it appears. Just create a var of type Date and set its value from the datePicker outlet like this.
@IBOutlet weak var yourDatePicker: NSDatePicker!
var date = Date()
@IBAction func datePickerChanged(_ sender: Any) {
date = yourDatePicker.dateValue
}
Now you can use that variable to insert date values on Core Data's attributes of type Date or something like that.
Get hour and minute in swift 5
let comp = datePickerOutlet.calendar.dateComponents([.hour, .minute], from: datePickerOutlet.date)
print(comp.hour!)
print(comp.minute!)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.