How do you make UIDatePicker a 24 hour system - ios

I have a UIDatePicker that is set to the hour the minutes then AM/PM. How do I make it so that it is set to the 24 hour system like in the UK? For example 1 would be 13 and there wouldn't be AM or PM.

var datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Time
datePicker.locale = NSLocale(localeIdentifier: "en_GB") // using Great Britain for this example

Using Swift 4
I have used the following the method to help me achieve a time-picker without AM / PM.
Note i am using TextField as Inputview
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
showTimePicker()
return true
}
func showTimePicker() {
timePicker.datePickerMode = .time
timePicker.locale = Locale(identifier: "en_GB") // Change to your locale
let toolbar = UIToolbar();
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneTimePicker));
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelTimePicker));
toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
modifiedHoursTextField.inputAccessoryView = toolbar
modifiedHoursTextField.inputView = timePicker
}
#objc func doneTimePicker() {
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
modifiedHoursTextField.text = timeFormatter.string(from: timePicker.date)
self.view.endEditing(true)
}
#objc func cancelTimePicker() {
self.view.endEditing(true)
}

Bonus to JAL's answer, if you also want to be able to pick "date", you can use something like below:
viewDidLoad:
deadlineTF.inputView = deadlineDatePicker
deadlineDatePicker.timeZone = NSTimeZone.local
deadlineDatePicker.datePickerMode = UIDatePickerMode.dateAndTime
deadlineDatePicker.locale = Locale(identifier: "tr_TR")
deadlineDatePicker.backgroundColor = UIColor.white
deadlineDatePicker.layer.cornerRadius = 5.0
deadlineDatePicker.layer.shadowOpacity = 0.5
deadlineDatePicker.addTarget(self, action: #selector(onDidChangeDate), for: .valueChanged)
.
The Function:
// called when the date picker called.
#objc func onDidChangeDate(sender: UIDatePicker){
// date format
let myDateFormatter: DateFormatter = DateFormatter()
myDateFormatter.dateFormat = "dd/MM/yyyy HH:mm"
// get the date string applied date format
let mySelectedDate = myDateFormatter.string(from: sender.date)
deadlineTF.text = mySelectedDate
}

Related

How to make UIDatePicker update textfield and database in Swift 4

In my app I have a form that has a textField that pulls up a UIDatePicker when clicked. When I select a new date from the UIDatePicker the textField does not update.
When debugging it seems like when a new date is selected the action isn't registered and it just sends over the same date.
Below is my code (Which I am planning on refactoring/cleaning up after resolving this issue)
import UIKit
import RealmSwift
class ClientDetailsViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
let realm = try! Realm()
//Create Picker Views
let dateAppointedPickerView = UIDatePicker()
#IBOutlet weak var clientDateAppointedText: UITextField!
var selectedClient : Client? {
//Everything in the did set function will happen as soon as this variable is set with a value
didSet {
loadClientDetails()
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Assign Picker Views
setPickerViews()
//Assign Picker View Settings
setPickerViewSettings()
//Assign Picker View Delegates
setDelegates()
}
//MARK: - Date Format Method
func formatDateToString(_ date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale.current
let formattedDate = dateFormatter.string(from: date)
return formattedDate
}
func formatStringToDate(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale.current
let formattedDate = dateFormatter.date(from: dateString)
return formattedDate!
}
func loadClientDetails() {
loadViewIfNeeded()
clientDateAppointedText.text = formatDateToString((selectedClient?.dateAppointed)!)
}
//Send textfield/picker data to database
func textFieldDidEndEditing(_ textField: UITextField) {
var clientData : String = ""
guard let currentClient = selectedClient else {fatalError()}
switch textField {
case clientDateAppointedText:
clientData = "clientDateAppointedText"
updateClientDetails(currentClient, clientData)
default:
print("Did not edit anything")
}
}
//MARK: - Data Manipulation Methods
func updateClientDetails(_ clientInfo: Client,_ clientString: String) {
let editClient : String = clientString
do {
try realm.write {
switch editClient {
case "clientDateAppointedText":
clientInfo.dateAppointed = formatStringToDate(clientDateAppointedText.text!)
default:
print("Unable to edit client information")
}
}
} catch {
print("Unable to save client details")
}
}
I expect the Date Picker to update the textview every time a new date is chosen and for the value to be passed to the database to be updated. The actual result is that the value passed is the same date over and over again.
Steps to do it:
First intialize pickerview
var datePickerView:UIDatePicker = UIDatePicker()
Create action of textfield through storyboard i.e "Editing Did Begin"
#IBAction func textEditing(_ sender: UITextField)
{
isPickUpSelected = true
datePickerView = UIDatePicker()
datePickerView.minimumDate = Date()
datePickerView.date = selectedPickupDate
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action:
#selector(TUGBestDealVC.datePickerValueChanged), for:
UIControlEvents.valueChanged)
self.addToolBar(picker: datePickerView, textField: sender)
}
Write addToolbar function to customize datepicker:
func addToolBar(picker: UIDatePicker, textField: UITextField)
{
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.darkGray
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: TUGHelpers().getLocalisedString(strKey:
"DONE"),style: .plain, target: self,
action:#selector(TUGBestDealVC.doneClick(sender:)))
doneButton.tag = picker.tag
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target:
nil,action: nil)
let cancelButton = UIBarButtonItem(title:"Cancel", style: .plain, target: self,
action:#selector(TUGBestDealVC.cancelClick(sender:)))
cancelButton.tag = picker.tag+4
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
Track action of datepicker change date:
func datePickerValueChanged(sender:UIDatePicker)
{
self.setPickupDate(date: sender.date)
}
Here is done action of datepickerview:
#objc func doneClick(sender: UIButton)
{
self.setPickupDate(date: datePickerView.date)
dateTxt.resignFirstResponder()
}
Here is cancel action of datepickerview:
#objc func cancelClick(sender: UIButton)
{
dateTxt.resignFirstResponder()
}
Here you will get the date of pickerview:
func setPickupDate(date: Date)
{
print(date)
}
The same code you can update in the database every time
Enjoy, Happy coding.

How to set a default date value in a inputView

I would like to set a default date value in inputView.
I have:
func createDatePickerDgeb1() {
datePickergeb.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedgeb1))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.setItems([spaceButton,doneButton], animated: false)
gebdatum.inputAccessoryView = toolbar
gebdatum.inputView = datePickergeb
}
The picker view shows me current date. Is possible that I can show for example the "01.01.1960" as a default?
// Create date components
var dateComponents = DateComponents()
dateComponents.year = 1960
dateComponents.month = 1
dateComponents.day = 1
// Create date from components
let userCalendar = Calendar.current // user calendar
let date = userCalendar.date(from: dateComponents)
// Set datePicker date
datePickergeb.setDate(date, animated: false)

How do I print the age based on the selected date picker on a text field?

When I select the date the app stops responding. I want to select the date and show it in a textfield without pressing a done button. So I want to see date in live.
How do I print the age based on the selected Date picker on a TextField?
import UIKit
import Firebase
class SignUpEmailSegue0: UIViewController {
#IBOutlet weak var dateBirthday: UITextField!
#IBAction func dateBirthdayEdit(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MMM/yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
}
Try changing your code as follows - using #selector() and exposing your function to #objc
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
To answer your second question of how to get the age:
let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: sender.date, to: Date())
if let age = ageComponents.year {
print(age)
}

UIDatePicker minimumDate and maximumDate

I'm trying to set a minimum and maximum date to limit the selection of the user, but it doesn't work:
override func viewDidLoad() {
let datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
tfDateNaissance.inputView = datePickerView
let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let currentDate: NSDate = NSDate()
let components: NSDateComponents = NSDateComponents()
components.year = -18
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
components.year = -150
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
let pickerToolBar = UIToolbar()
pickerToolBar.barStyle = UIBarStyle.Black //you can change the style
pickerToolBar.translucent = true
pickerToolBar.tintColor = UIColor.whiteColor() // or other colours
pickerToolBar.sizeToFit()
let spaceButtonPicker = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButtonPicker = UIBarButtonItem(title: "Ok", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelDatePicker:")
pickerToolBar.setItems([cancelButtonPicker, spaceButtonPicker], animated: false)
pickerToolBar.userInteractionEnabled = true
tfDateNaissance.inputAccessoryView = pickerToolBar
}
func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
//
// dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
tfDateNaissance.text = dateFormatter.stringFromDate(sender.date)
}
func cancelDatePicker(sender: UIBarButtonItem){
if tfProjet.isFirstResponder(){
tfProjet.resignFirstResponder()
} else if tfDateNaissance.isFirstResponder(){
tfDateNaissance.resignFirstResponder()
}
}
I found this code on stack overflow, I get no errors, but I can select 2200 as year for exemple. I think it's because it's an input view, so how to to ?
The minDate was later than the maxDate:
components.year = -150
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
components.year = -18
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate

swift not updating textfield.text using UIDatePicker

In swift, I have a textField programmatically declared.
override func viewDidLoad() {
super.viewDidLoad()
textField3.delegate = self
textField3.returnKeyType = UIReturnKeyType.Next;
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
textField3.inputView = datePicker
}
func handleDatePicker(sender: UIDatePicker) {
textField3.text = dateFormatter.stringFromDate(sender.date)
}
All the other questions I've found similar to this deal with interface builder, and haven't helped. How would i fix this programmatically?
Xcode 9 • Swift 4
#objc func handleDatePicker(_ datePicker: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker), forControlEvents: .valueChanged)
}
extension Date {
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter
}()
var formatted: String {
return Date.formatter.string(from: self)
}
}
Swift 3 version of #Leo Dabus answer:
func handleDatePicker(sender: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: UIControlEvents.valueChanged)
}
extension Date {
var formatted: String {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter.string(from: self as Date)
}
}
In, Swift 4
confirm to UITableViewDelegate
make txtFChequeDate.delegate = self
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
txtFChequeDate.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
if txtFChequeDate.text == "" {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: Date())
}
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: sender.date)
}

Resources