我创建了IBOutlet一个日期选择器。
@IBOutlet weak var logDate: UIDatePicker!
我还将mode此日期选择器的 设置为date。
我有没有办法提取用户输入日期选择器的日期?
我尝试使用print(logdate),但是它也给了我日期和时间。像这样2015-10-30 07:10:03 +0000
也许你想要这个:
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
Run Code Online (Sandbox Code Playgroud)
或者你可能想要这个:
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
Run Code Online (Sandbox Code Playgroud)
您可以尝试其他dateStyle设置,或者通过设置dateFormat属性更明确。该dateFormat语法越晦涩。请记住对格式的年份部分使用yyyy,而不是 YYYY。但它MM,不是 mm月份部分。例子:
formatter.dateFormat = "yyyy-MM-dd"
print(formatter.stringFromDate(logDate.date))
// Output: 2015-10-31
Run Code Online (Sandbox Code Playgroud)
您可以使用此代码提取用户在日期字段中输入的日期。注意:此解决方案将输入提取为字符串
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)
Run Code Online (Sandbox Code Playgroud)
使用了以下代码段: http: //www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift
| 归档时间: |
|
| 查看次数: |
14190 次 |
| 最近记录: |