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
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.
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.
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)
}
How can I compare the values from data Base to my current date ? A date is saved in the data base when some action is performed, I need to compare that date with my current date and do some action. How can I do that ?
The date is saved my date base in this format:
var tasksin2 : Task?
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
let mydate="\(dateFormatter.string(from: datePicker.date))"
tasksin2?.time=mydate
(UIApplication.shared.delegate as! AppDelegate).saveContext()
Here ya go:
extension String {
func toDate() -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy hh:mm"
return formatter.date(from: self)
}
}
class MyViewController: UIViewController {
var dateString1: String!
var dateString2: String!
override func viewDidLoad() {
super.viewDidLoad()
// set dateStrings
printDateTypes()
}
func printDateTypes() {
guard let date1 = dateString1.toDate() else {
print("dateString1: \(dateString1) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
guard let date2 = dateString2.toDate() else {
print("dateString2: \(dateString2) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
let isDescending = date1.compare(date2) == ComparisonResult.orderedDescending
print("orderedDescending: \(isDescending)")
let isAscending = date1.compare(date2) == ComparisonResult.orderedAscending
print("orderedAscending: \(isAscending)")
let isSame = date1.compare(date2) == ComparisonResult.orderedSame
print("orderedSame: \(isSame)")
}
}