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)
}
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
}
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.
What I am trying to accomplish:
I am trying to make an enter button that checks the date in the UITextField to see if it is before the current date(any date that is today) and if the date in the UITextField is in the past, I want to throw an error/alert to tell the user to enter a date in the future--possibly a week or month from the current date.
A little background:
I made a viewController with a textfield that a user is going to enter a
date into and the way this works is the user presses on the textField and
a datePicker pops up allowing them to update the textField with the datePicker.
The problem I am running into:
This all works fine until I want to compare the date in the textField with the current date. This is because the date in the textField is a string and not a date that NSDate can recognize.
My question basically is
How do I convert the string date in the TextField into a format that NSDate can recognize?
Here is my code for my enterButton function:
#IBAction func enterButton(sender: AnyObject) {
let dateFormatter = NSDateFormatter()
var raceDate = raceDateTextField.text
let currentDate = NSDate()
raceDate = dateFormatter.stringFromDate(sender.date)
if currentDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
}
I'm getting the error
cannot convert value of type 'String?' to expected argument type 'NSDate' # the line below
if currentDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
Here is the my code for updating my textField using a datePicker just for reference:
#IBAction func textFieldEditing(sender: UITextField) {
let datePicker:UIDatePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePicker
datePicker.addTarget(self, action: #selector(SecondViewController.datePickerValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
raceDateTextField.text = dateFormatter.stringFromDate(sender.date)
}
Am I going about this wrong logically?
Any help with this will be greatly appreciated! :)
EDIT/UPDATE!
I made the changes like you guys advised and I am getting the same error at the same line.
Here is my updated code:
#IBAction func enterButton(sender: AnyObject) {
let dateFormatter = NSDateFormatter()
var raceDate = raceDateTextField.text
dateFormatter.dateFormat = "dd/MM/yyyy"
var minimumDate: NSDate? = NSDate()
raceDate = dateFormatter.stringFromDate(sender.date)
if minimumDate!.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date")
}
}
I think the (sender.date) parameter is wrong # line:
raceDate = dateFormatter.stringFromDate(sender.date)
Right now I'm thinking I entered in the wrong parameter(sender.date) because raceDate still shows up as a string data type in the if statement.
Swift 3:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyy"
let raceDate = raceDateTextField.text
let date = dateFormatter.date(from: raceDate!)
let minimumDate = NSDate()
if minimumDate.compare(date!) == ComparisonResult.orderedDescending {
}
The text that is currently in your textField is a String. You need to run that through a dateFormatter and get the date (NSDate). Afterwards you can compare it to the current date.
It's basically the same thing as when you set the text in your textField, but the other way around.
see: https://developer.apple.com/reference/foundation/nsiso8601dateformatter/1643127-datefromstring
You said that you want to compare the date in the textField with the current date.
So just create and set a minimum date for the date picker to today. var minimumDate: NSDate?
For example:
if minimumDate.compare(raceDate) == NSComparisonResult.OrderedDescending {
print("Race Date is earlier than Current Date. Are you a time traveler?")
}
#IBAction func enterButton(sender: AnyObject) {
let myDate = raceDateTextField.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)
}
Got it working correctly, thanks to #Amit Jagesha, #tymac, #Andrei Filip, and #Leo Dabus
Here is the end product in case anybody else has a similar problem and for future reference.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyy"
let raceDate = raceDateTextField.text
let date = dateFormatter.dateFromString(raceDate!)
let minimumDate = NSDate()
if minimumDate.compare(date!) == NSComparisonResult.OrderedDescending {
}
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.