I am trying to make a UIButton put the current time in a text field when pressed? Here is the textfield and UIButton code I have:
#IBOutlet weak var f1TextField: UITextField!
#IBAction func markf1(_ sender: UIButton) {
timeatf1TextField.becomeFirstResponder;
timeatf1TextField.text! = "Time". // This is where I want the current time to go!
}
You're declaring the variable as f1TextField and calling it as timeatf1TextField. To get current time see the code below...
#IBOutlet var f1TextField: UITextField!
#IBAction func markf1(_ sender: Any) {
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "HH:mm:ss a"
let dateString = formatter.string(from: now)
f1TextField.text = dateString
}
try this,
#IBAction func markf1(_ sender: UIButton) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" //Dateformat you want
let date = Date()
let dateString = dateFormatter.string(from: date)
timeatf1TextField.text = dateString
}
Related
If you look at the iPhone alarm app I can see that if I don't set the time in the date picker, the alarm is set to the current time.
#IBAction func selectAlarm(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
let date = dateFormatter.string(from: datePicker.date)
print("date : \(date)")
}
The above code outputs the time set when the datePicker is moved. How to output current time as default without moving datePicker as above?
Try this
#IBAction func selectAlarm(_ sender: Any) {
let newDatePicker = UIDatePicker()
newDatePicker.date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let currentTime = dateFormatter.string(from: newDatePicker.date)
print("time : \(currentTime)")
self.yourTextField.text = currentTime
}
Put the datePicker.date outside the func selectAlarm(), eg: in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.datePickerMode = .time
datePicker.date = Date()
}
The date Picker works and gives date even without moving datePicker. I have tested it.
#IBAction func getCurrentTime() {
var formatter = DateFormatter()
formatter.dateFormat = "DD/MM/YY"
var dd = formatter.string(from: datePicker.date)
print(dd)
}
Problem is with your code.
When I use DatePicker to set date
It said it was nil
Despite I checked the date string format is correct
And dateFormat is set to format that I want.
Here's code
class DatePickerViewController: UIViewController {
var originDate: String!{
didSet{
//print("\(originDate)") is like "2019/07/12"
selectedDate = dateFormatter.date(from: originDate)
//print("\(selectedDate)") is nil
datePicker.setDate(selectedDate, animated: true)
}
}
var selectedDate: Date!
var dateString: String = "yyyy/MM/dd"
var dateFormatter: DateFormatter = DateFormatter()
override func viewDidLoad() {
dateFormatter.dateFormat = dateString
}
The ShowPickerViewController call DatePickerViewController
class ShowPickerViewController:UIViewcontroller {
#IBAction func showDatePicker(_ sender: Any) {
let vc = DatePickerViewController()
vc.originDate = sender.text // "2019/07/12"
present(vc, animated: true)
}
}
Initialize the date formatter with a closure
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
return formatter
}()
and delete the line in viewDidLoad
What I want to do, is to retrieve date from string where it's saved, and pass it to UIDatePicker (scrolling date picker element), so here is my piece of code:
#IBOutlet weak var myDatePicker: UIDatePicker!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var saveButton: UIBarButtonItem!
//converting date to string to show in table cell
func dateToString (date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
return dateFormatter.stringFromDate(date)
}
//converting string from table cell to edit date
func stringToDate (string: NSString) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
return dateFormatter.dateFromString(dateToString (myDatePicker.date))!
}
// here we are saving our data picked from text field and date picker UIs
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let date = dateToString (myDatePicker.date) ?? ""
item = Item (name: name, date: date)
}
}
// Here we are retrieving data when press tableCell cell:
override func viewDidLoad() {
super.viewDidLoad()
if let item = item {
nameTextField.text = item.name
myDatePicker.setDate(stringToDate(item.date), animated: true)
// also need to pass date smhw
}
}
Saving from UIDatePicker to string in UITableCell - no problem, passing string (UILabel) to UITextField - no problem, but I can not pass string to UIDatePicker.
It's no warnings, build - no problem, launch, but no action happened.
Please suggest the solution on this issue. I am coding swift 1.2.
func stringToDate (string: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
return dateFormatter.dateFromString(string)!
}
This works.
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:
#IBAction func dateToString(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
var strDate = dateFormatter.stringFromDate(myDatePicker.date)
return ()
}
But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):
#IBOutlet weak var saveButton: UIBarButtonItem!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let date =
item = Item (name: name, date: date)
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let item = item {
nameTextField.text = item.name
= item.date
}
}
please help, what should I write in
let date =
and
= item.date
to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!
You could change your function like
var strDate:String = String()
#IBAction func dateToString(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
strDate = dateFormatter.stringFromDate(myDatePicker.date)
}
Then you can use
let date = strDate
First, your dateToString function shouldn't be an IBAction. Those are used for methods called directly by interface items and hooked up in Interface Builder. What you want here is a regular function that takes a date and returns a formatted string, like this:
func dateToString(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
return dateFormatter.string(from: date)
}
Now when you want a formatted date string, you call it and pass it the Date you want it to format. It looks like you're using a UIDatePicker to specify the date, so you need to set up an #IBOutlet in your view controller (if you haven't already done so) to give you access to that object. To do that, control-drag from the date picker to your view controller source, then name the outlet. It will generate code in your source like:
#IBOutlet weak var myDatePicker: UIDatePicker!
Now you can refer to the datePicker elsewhere in your class. So you can get the date as a formatted string like this:
let dateString = dateToString(date: myDatePicker.date)
You can then pass this string to an Item, or set it as the text of a field or label.
This is how I figured it out:
func dateToString (date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
return dateFormatter.stringFromDate(date)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let date = dateToString (myDatePicker.date) ?? ""
item = Item (name: name, date: date)
}
I'm using a textfield that uses a datePicker instead of a keyboard. It displays the format as a string that looks like this 'May 31, 2015 at 12:30'(taken from the println(delivery.text) function.) I want to change the date to NSDate, so I can compare to current date. Any suggestions?
#IBOutlet weak var pickUp: UITextField!
#IBOutlet weak var delivery: UITextField!
let dateFormat: NSDateFormatter = NSDateFormatter()
let datePicker: UIDatePicker = UIDatePicker()
let dateFormat2: NSDateFormatter = NSDateFormatter()
let datePicker2: UIDatePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
dateFormat.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat.timeStyle = NSDateFormatterStyle.LongStyle
datePicker.datePickerMode = UIDatePickerMode.DateAndTime
datePicker.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
pickUp.inputView = datePicker
dateFormat2.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat2.timeStyle = NSDateFormatterStyle.LongStyle
datePicker2.datePickerMode = UIDatePickerMode.DateAndTime
datePicker2.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
delivery.inputView = datePicker2
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.toolbarHidden = false
self.tabBarController?.tabBar.hidden = true
}
func updateDateField(sender: UIDatePicker) {
if sender == datePicker
{
pickUp.text = dateFormat.stringFromDate(sender.date)
}
if sender == datePicker2
{
delivery.text = dateFormat2.stringFromDate(sender.date)
}
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy 'at' h:mm:ss a"
if let date = dateFormatter.dateFromString("May 31, 2015 at 12:30:15 PM") {
println(date)
}
if you need some reference for date formatting you can use this one:
You can try using the DateFormatter to format your string into a date and then pulling the NSDate object out like so. In your case, something like this would probably suit your needs.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy at H:mm"
let date = dateFormatter.dateFromString(//insert string here)
Refer to the original documentation if you have further questions or this handy guide for formatting guidelines.