How to convert date picker value into String type in Swift 3.0 ?
Right now I have managed to create date picker but the value that appear in textfield is today's date which is 2/8/17, m/d/yy format.
My goal is to convert m/d/yy into String and the date value will be 2017-02-08, yyyy/mm/dd format
The code as below.
Date.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var dateTxt: UITextField!
let datepicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
displayDate()
}
func displayDate(){
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePick))
toolbar.setItems([doneBtn], animated: false)
dateTxt.inputAccessoryView = toolbar
dateTxt.inputView = datepicker
}
func donePick(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateTxt.text = dateFormatter.string(from: datepicker.date)
self.view.endEditing(true)
}
}
Can anyone help ?
Thanks.
For that you need to set dateFormat property of DateFormatter not the dateStyle and timeStyle.
func donePick(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateTxt.text = dateFormatter.string(from: datepicker.date)
self.view.endEditing(true)
}
Related
Im just trying to extract a date to a variable to be used somewhere else and to have that variable change everytime the value of the Picker changes.
#IBAction func datePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
var DateString = dateFormatter.string(from: sender.date)
return
}
Im sure its simple but Im a newbie.
Thank you
Try this
make an extension on Date
extension Date {
func convertDateToString(format : String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
in your VC
let dateFormat = "yyyy/MM/dd"
var currentDate = Date().convertDateToString(format: dateFormat) // to get current date
#IBAction func datePicker(_ sender: UIDatePicker) {
currentDate = sender.date.convertDateToString(format: dateFormat)
}
Use a property observer. It's called whenever the value changes.
var selectedDate : Date = Date() {
didSet {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy/MM/dd"
dateDisplay.text = dateFormatter.string(from: selectedDate)
}
}
#IBAction func datePicker(_ sender: UIDatePicker) {
selectedDate = sender.date
}
Declare it inside the vc
var currentDate = ""
#IBAction func datePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
currentDate = dateFormatter.string(from: sender.date)!
}
I'm trying to populate a pickerView with a default value (String). Currently I'm able to capture it's value as a time after the user interacts with it, however I'm not able to set the time value before it becomes visible to the user.
I've tried
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
however that errors "Value of type '(UIDatePicker) -> ()' has no member 'setDate'"
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
//my attempt at passing in a string
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
tempTime = (dateFormatter.string(from: sender.date))//successfully captures the user's input value
}
Here's the function that launches the xib (containing the timePicker)
func showSomeDialogue() {
let newVC = SomeViewContoller(nibName: "SomeViewController", bundle: nil)
let popup = PopupDialog(viewController: newVC,
buttonAlignment: .horizontal,
transitionStyle: .bounceUp,
tapGestureDismissal: true,
panGestureDismissal: false)
present(popup, animated: true, completion: nil)
newVC.someDelegate = self as SomeDelegate
}
The xib's class
import UIKit
protocol MealDelegate {
func didCreateMeal(mealTime: String)
}
class SomeViewContoller: UIViewController {
var someDelegate: SomeDelegate!
var tempTime = ""
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
tempTime = (dateFormatter.string(from: sender.date))
}
#IBAction func someSaveBtn(_ sender: UIButton) {
mealDelegate.didCreateMeal(mealTime: tempTime)
self.dismiss(animated: true, completion: nil)
}
}
Add following to your view controller class:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "09:00 AM")
timePicker.date = date
Add the following to your SomeViewController class:
//MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "10:57 PM")
//or whatever date you want to display as default
timePicker.setDate(date, animated: true)
}
Try this,
#IBAction func timePicker(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .dateAndTime
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleTimePicker(sender:)), for: .valueChanged)
}
#objc func handleTimePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "
tempTime = dateFormatter.string(from: sender.date)
// view.endEditing(true)
}
I'm using DatePicker with my country timeZone year month day are okay but there is AP prefix on picker which I don't need how can I get ride of it ?
I have searched a lot but there is nothing about it
update :
override func viewDidAppear(_ animated: Bool) {
datepicker2.datePickerMode = .date
datepicker2.timeZone = TimeZone(identifier: "IRST")
datepicker2.calendar = Calendar(identifier: .persian)
datepicker2.locale = Locale(identifier: "fa_IR")
datepicker2.date=self.minDate
datepicker2.addTarget(self, action: Selector("datepickerAction"), for: .valueChanged)
}
I need my native date and my time zone and this is datePicker initializing
func datepickerAction(){
let date = self.datepicker2.date
let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
let yr=components.year
print(hour,minute,yr)
}
this is the listener which is not working properly not change the date. each time print the same date.
screenshot
http://uploadkon.ir/2Ui
I think you have to pass the parameter in the function like this...
override func viewDidAppear(_ animated: Bool) {
datepicker2.datePickerMode = .date
datepicker2.timeZone = TimeZone(identifier: "IRST")
datepicker2.calendar = Calendar(identifier: .persian)
datepicker2.locale = Locale(identifier: "fa_IR")
datepicker2.addTarget(self, action: #selector(datepickerAction(_:)), for: .valueChanged)
}
So, now you can get the date every time that change in the picker...
func datepickerAction(_ sender: UIDatePicker){
let date = self.datepicker2.date
let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
let yr=components.year
print(hour,minute,yr)
}
So I am creating a contact phonebook app and I am trying to get the keyboard to display as a DateTimePicker.
I have gotten the keyboard to work after some time but I can't seem to get the formatter working correctly.
#IBOutlet weak var datetxt: UITextField!
var datepicker = UIDatePicker()
func createdatepicker() {
datepicker.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let donebutton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneac))
toolbar.setItems([donebutton], animated: true)
datetxt.inputAccessoryView = toolbar
datetxt.inputView = datepicker
}
func doneac() {
let Date = DateFormatter()
Date.dateStyle = .short
//Date.string(from: String)
datetxt.text = "\(datepicker.date)"
self.view.endEditing(true)
}
When I run the app it selects the date but, it also shows the time in the text field.
You're not using your DateFormatter. The datetxt.text = "\(datepicker.date)" simply sets the text to the description of the date picker's date (which includes date and time). But you're not using your formatter at all.
And, by the way, I wouldn't use Date for the name of the date formatter. One would generally use formatter or dateFormatter. Date only invites confusion with the Swift type of the same name.
Thus, you might do:
let formatter = DateFormatter()
formatter.dateStyle = .short
datetxt.text = formatter.string(from: datepicker.date)
here you can make use of formatter you had not showed any date formatter you used
//here is current date
let date = Date()
//formatter to return value as 21-11-2017
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
//Date Output
let result = formatter.string(from: date)
//second formatter to return time format like 2:31 Am
let formatter1 = DateFormatter()
formatter1.dateFormat = "h:mm a"
//Time Output
let result1 = formatter1.string(from: date)
//set values for example using label for reference
DateLabel.text = result
TimeLabel.text = result1
//actual output is as Follows:
DateLabel = 21-11-2107
TimeLabel = 9:54 AM
I have a textfield and when it is selected a datepicker pops up instead of a keyboard, but it only updates with todays date the first time. The user changes the date, but the textfield does not continue to update. What is the problem?
This is how I call the Datepicker and control the date being inputted into my textfield:
#IBAction func dp(sender: UITextField) {
var DatePickerView : UIDatePicker = UIDatePicker()
DatePickerView.datePickerMode = UIDatePickerMode.Date
textfieldjobdate.inputView = DatePickerView
DatePickerView.addTarget(self, action: Selector("handleDatePicker"), forControlEvents: UIControlEvents.ValueChanged)
}
func handleDatePicker() {
var DatePickerView : UIDatePicker = UIDatePicker()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
textfieldjobdate.text = dateFormatter.stringFromDate(DatePickerView.date)
}
Your handleDatePicker method is instantiating a new DatePicker each time it's called. You need to add a parameter to the function to pass in the sender (the DatePicker created in func dp)
#IBAction func dp(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
textfieldjobdate.text = dateFormatter.string(from: sender.date)
}
let selectedDate = datePicker.date
print(selectedDate)
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let strDate = formatter.string(from: selectedDate)
self.labelDate.text = strDate
datePicker = UIDatePicker(frame:CGRect(x: 0, y: self.view.frame.size.height-180 , width: self.view.frame.size.width, height: 200))
self.view.addSubview(datePicker)
datePicker.datePickerMode = UIDatePickerMode.dateAndTime
datePicker.isHidden = true
button.isSelected = false
datePicker.addTarget(self, action: #selector(self.dateSelected), for: UIControlEvents.valueChanged)
#objc func dateSelected()
{
let dateformatter1 = DateFormatter()
dateformatter1.dateFormat = "ccc, d MMM yyy"
let dateString1 = dateformatter1.string(from: datePicker.date)
print("Date Selected \(dateString1)")
labelDate.text = dateString1
let dateformatter2 = DateFormatter()
dateformatter2.dateFormat = "dd-MM-yyyy"
let dateString2 = dateformatter2.string(from: datePicker.date)
print("Date Selected \(dateString2)")
let dateformatter3 = DateFormatter()
dateformatter3.dateFormat = "dd/MM/yyyy"
let dateString3 = dateformatter3.string(from: datePicker.date)
print("Date Selected \(dateString3)")
let dateformatter4 = DateFormatter()
dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
let dateString4 = dateformatter4.string(from: datePicker.date)
print("Date Selected \(dateString4)")
}
This article on DatePicker and NSDateFormat helped me a lot.