I have the code below to calculate the days difference between 2 dates. First view is where i pick a date from UIDatePicker() , press a button to segue to the second view and to calculate days difference between the selected date and today's date and pass the result to the second view to be shown.
I just cant get the function to calculate the time difference to work. Is there something wrong im doing? Im sorry in advance as i've just started learning swift.
on my code
Calendar.current.dateComponents([.day], from: self.GetDate,to: datePicker.date).day! i get this error below
Type 'Any' has no member 'day'
-
first view.
import UIKit class ViewController: UIViewController { @IBOutlet weak var dateInput: UITextField! let datePicker = UIDatePicker() var GetDate = "" override func viewDidLoad() { super.viewDidLoad() CreateDatePicker() } // Create Date func CreateDatePicker() { datePicker.datePickerMode = .date dateInput.inputView = datePicker let toolbar = UIToolbar() toolbar.sizeToFit() let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked)) toolbar.setItems([doneButton], animated: true) dateInput.inputAccessoryView = toolbar } @objc func doneClicked() { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none dateInput.text = dateFormatter.string(from: datePicker.date) self.view.endEditing(true) } @IBAction func GetDateButton(_ sender: Any) { self.GetDate = dateInput.text! performSegue(withIdentifier: "toTime", sender: self) Calendar.current.dateComponents([.day], from: self.GetDate,to: datePicker.date).day! } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as! timeDiffr vc.textDisplay = self.GetDate } } Second view
import Foundation import UIKit class timeDiffr: UIViewController { @IBOutlet weak var labeltext: UILabel! var textDisplay = "" override func viewDidLoad() { super.viewDidLoad() labeltext.text = textDisplay } }
dateComponents.Datefor thefromparameter. You are trying to give it aString.Calendar.current.dateComponents([.day], from: self.GetDate,to: datePicker.date).day!, please notice thatfromshould be an instance ofDate, not aString@MustafaAljaburidateComponentsmethod takes 2 dates, so you need to pass aDateinstead of string