[英]Get date from date picker in swift
I have created an IBOutlet
to a date picker.我已经为日期选择器创建了一个IBOutlet
。
@IBOutlet weak var logDate: UIDatePicker!
I have also set the mode
of this date picker to date
.我还将此日期选择器的mode
设置为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.我尝试使用print(logdate)
,但是它也给了我日期和时间。 Like this 2015-10-30 07:10:03 +0000
像这样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.您可以尝试另一个dateStyle
设置,或者通过设置dateFormat
属性来更明确。 The dateFormat
syntax can get pretty hairy. dateFormat
语法可能会变得非常麻烦。 Remember to use yyyy
, not YYYY
, for the year part of your format.请记住对格式的年份部分使用yyyy
,而不是YYYY
。 But it's MM
, not mm
for the month part.但它是MM
,而不是月份部分的mm
。 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使用了一段代码: http : //www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift
Swift 5斯威夫特 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.只需创建一个 Date 类型的 var 并像这样从 datePicker 插座设置它的值。
@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.现在您可以使用该变量在 Core Data 的 Date 类型或类似类型的属性上插入日期值。
Get hour and minute in swift 5在 swift 5 中获取小时和分钟
let comp = datePickerOutlet.calendar.dateComponents([.hour, .minute], from: datePickerOutlet.date)
print(comp.hour!)
print(comp.minute!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.