Swift: using UIDatePicker as UITextField inputView not updating - datepicker

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.

Related

How can capture a date from UIDatePicker to an outside variable

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)!
}

is there a way to set an array of dates all to the same Hour?

I have an array of dates created from a date picker. When they are saved it also adds the hours and minutes. When I compare the dates to be equal some of them are an hour off because of daylight savings time.
Is there a way, after the date picker, to set each date to the same hour or do I have to go through the process of checking for daylight savings time and adding or subtraction an hour? Or should I run the array through a function to make them all equal?
func createDatePicker() {
// format Display of date
datePicker.datePickerMode = .date
// assign datepicker to textfield
dateTextField.inputView = datePicker
// create toolbar
let toolBar = UIToolbar()
toolBar.sizeToFit()
// add item Button
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector (doneClicked))
toolBar.setItems([doneButton], animated: true)
dateTextField.inputAccessoryView = toolBar
}
#objc func doneClicked() {
//format the date display in text field
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "MM-dd-yyyy"
dateTextField.text = dateFormatter.string(from: datePicker.date)
self.view.endEditing(true)
found a fix.
if let date = dateTextField.text {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
newDate = dateFormatter.date(from: date)!
let tz = TimeZone.current
if tz.isDaylightSavingTime(for: newDate) {
print("date Changed")
newDate += 3600

myLabel display the wrong name (UIDatePicker)

I have a problem, my label displays the wrong month name after selected from DatePicker.
img app
Code:
let myDatePicker: UIDatePicker = {
let pv = UIDatePicker()
pv.datePickerMode = .date
pv.locale = Locale(identifier: "de_DE")
pv.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)
return pv
}()
#objc func datePickerValueChanged(datePicker: UIDatePicker) {
let format = "dd MMM, yyyy"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
let dateValue = dateFormatter.string(from: datePicker.date)
myLabel.text = dateValue
}
let myLabel: UILabel = {
let label = UILabel()
return label
}()
P.S I have an additional question how to set the language of months in DatePicker automatically with regional settings?
I tried (inside myDatePicker) : pv.locale = .current
First question:
You need to "localize" your dateFormatter, using
dateFormatter.locale = datePicker.locale
in your datePickerValueChanged
Second question:
You want to retrieve the correct month names as retrieved from the iPhone settings
Use Locale.autoupdatingCurrent instead of Locale(identifier: "de_DE")
. This gets the user preferred current locale, automatically up-to-date.

DateFormatter Swift 3

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

How to convert date picker value into String in swift 3.0?

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)
}