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.
Related
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
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
}
When I run this program and fill in the DOB field with my date of birth it does not populate to the "ageLabel" as it should. But it will print out when I include the print statement. If I don't include print statement I get the warning:
"Initialization of immutable value 'ageLabel' was never used; consider replacing with assignment to '_' or removing it"
What am I missing?
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var name: UITextField!
#IBOutlet weak var DOB: UITextField!
#IBOutlet weak var DOR: UITextField!
#IBOutlet weak var currentDate: UIDatePicker!
#IBOutlet weak var ageLabel: UILabel!
#IBAction func calculateButton(_ sender: Any) {
let textInput = DOB.text
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/YYYY"
let startDate = dateFormatter.date(from: textInput!)
let currentDate = Date()
let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let ageLabel = gregorian.components([.month, .year], from: startDate!, to: currentDate)
print (ageLabel)
}
}
You have an outlet named ageLabel which appears to the the label you wish to update.
In your calculateButton method, you have a local variable named ageLabel which is actually a DateComponents result that you don't use.
You make no attempt to update the actual label with the calculated age.
You are also using NSCalendar instead of Calendar. And your date format mistakenly uses YYYY instead of yyyy for the year.
You also assume the user actually enters a string in the very specific format of month slash year. If the user enters anything else your app will crash.
Here is a fixed version of your code:
#IBAction func calculateButton(_ sender: Any) {
let textInput = DOB.text!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
if let startDate = dateFormatter.date(from: textInput) {
let currentDate = Date()
let ageComponents = Calendar.current.dateComponents([.month, .year], from: startDate, to: currentDate)
ageLabel.text = "\(ageComponents.year!)"
} else {
ageLabel.text = ""
}
}
I just show the age in years. You can also show the months if you want.
Better yet, use a DateComponentsFormatter to show the age.
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 am teaching myself swift and I am still very new but I decided to make a simple app that prints the current time when you press a button. the code from the viewcontroller file is as follows:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var LblTime: UILabel!
#IBAction func BtnCalltime(sender: AnyObject) {
var time = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM"
var formatteddate = formatter.stringFromDate(time)
LblTime.text = time
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I am having an issue with the line:
LblTime.text = time
I keep getting the error:
Cannot assign a value of type 'NSDate' to a value of type 'String?'
I have tried using:
lblTime.text = time as! string?
And:
lblTime.text = time as! string
but it does still not work, I would be very appreciative of some help.
Thanks
You need use a value from formatter.
#IBAction func BtnCalltime(sender: AnyObject) {
var time = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM"
var formatteddate = formatter.stringFromDate(time)
LblTime.text = formatteddate
}
You made the string from an NSDate already, you just aren't using it.
lblTime.text = formatteddate
Date is now preferred over NSDate. It is an overlay class meaning both will work, but Date but has a lot of advantages, this answer lists some of those.
Here is how to format a date to a string using Date instead of NSDate.
var time = Date()
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedDateInString = formatter.string(from: time)
dateLabel.text = formattedDateInString
A great site to get the formatter strings is http://nsdateformatter.com/
I had no idea that "MMM d yyyy, h:mm:ss a" would equal Mar 1, 7:02:35 AM but the site makes it easy.