Question about setting datePicker time in Swift - ios

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.

Related

Set time also on a textfield after setting the date

I'm setting a date on my text field like so...
override func viewDidLoad() {
super.viewDidLoad()
showDatePicker()
}
func showDatePicker() {
datePickerStartDate.datePickerMode = .date
datePickerStartDate.addTarget(self, action: #selector(EventDetailViewController.startDatePickerSelect(sender:)), for: .valueChanged)
startDateTextfield.inputView = datePickerStartDate
}
#objc func startDatePickerSelect(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = .medium
startDateTextfield.text = formatter.string(from: sender.date)
}
This opens a datepicker on tap on the textfield and sets the date. But what I want is after I select the date, I want the time picker also to show up so that I can set the time also. And this time should get appended to the date that was set initially. How can I achieve that..?
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
You can get the time of your choice from the string as :
let timeStr = "2:00"
var time = dateFormatter.dateFromString(timeStr)
Or you can add and subtract specific time from the current date as :
//It will give you the time by adding 5 minutes to the current time you can use (-5*60) to get the time 5 minute back.
var date = Date().addingTimeInterval(TimeInterval(5*60))
var timeStr = dateFormatter.string(from: date)

UIButton pressed Insert Current Time in Text Field using Swift in Xcode

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
}

Can't Set a Converted Date from String as Minimum Date in DatePicker

I have two datepickers that contains time with format 7:00 AM and 8:00 PM for login and logout. These times may vary. I wanted to change the logout time and tried to use the login time as the minimum time but my code does not work, I can still select time like 1:00 AM or 6:00 AM as logout.
This is the code in my ViewDidLoad
if let actualLoginText = loginTextField.text {
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
formattedTime = formatter.date(from: start)!
}
And this is the code of my logout picker
#objc func timeOutPickerValueChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
timeOutPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 5, to: formattedTime)
logoutTextField.text = formatter.string(from: sender.date)
}
I also tried this but still doesn't work
if let actualLoginText = loginTextField.text {
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formattedTime = formatter.date(from: start)!
}
Thank you.
When working with dates / times, work with Date objects, not strings. The "string representation" should only be used to display the date/time to the user, not when manipulating the values.
Here is a simple example (assuming you have added two UIDatePickers and connected their Value Changed events). On load, it initializes the timeInPicker to the current date/time. Any time you select a new "Time In", the timeOutPicker.minimumDate is set to 5-minutes from the selected time, and the timeOutPicker.maximumDate is set to 8-hours from the minimum time:
class ViewController: UIViewController {
#IBOutlet weak var timeInPicker: UIDatePicker!
#IBOutlet weak var timeOutPicker: UIDatePicker!
let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateStyle = .short
df.timeStyle = .short
return df
}()
override func viewDidLoad() {
super.viewDidLoad()
// Initialize the TimeIn and TimeOut pickers to the current Date/Time
let now = Date()
updateTimeOutPicker(now)
}
func updateTimeOutPicker(_ withStartDateTime: Date) -> Void {
// add 5 minutes to the selected "In" time to get the "minimum time" for the Out Picker
guard let minDateTime = Calendar(identifier: .gregorian).date(byAdding: .minute, value: 5, to: withStartDateTime) else { return }
// add 8 hours to the to get the "maximum time" for the Out Picker
guard let maxDateTime = Calendar(identifier: .gregorian).date(byAdding: .hour, value: 8, to: minDateTime) else { return }
timeOutPicker.minimumDate = minDateTime
timeOutPicker.maximumDate = maxDateTime
print("New Min Out Time:", dateFormatter.string(from: minDateTime))
print("New Max Out Time:", dateFormatter.string(from: maxDateTime))
print()
}
#IBAction func timeInPickerValueChanged(_ sender: UIDatePicker) {
print("Selected In Time:", dateFormatter.string(from: sender.date))
print()
updateTimeOutPicker(sender.date)
}
#IBAction func timeOutPickerValueChanged(_ sender: UIDatePicker) {
print("Selected Out Time:", dateFormatter.string(from: sender.date))
print()
}
}
The login and logout time strings were pulled up from database. And when I don't edit the login textfield it's data remains as string since there was no value change, so I'm forced to use a string value as reference to my logout picker.
the result login being: 1999-12-31 23:00:00 +0000
and logout: 2018-01-04 22:24:20 +0000
this is the reason why using the login as my minimum time didn't work
so here's what I did, I added the current date so I can use it.
#objc func timeOutPickerValueChanged(sender: UIDatePicker) {
if let actualLoginText = loginTextField.text {
let date = Date()
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let nowTime = formatter.string(from: date)
let concat = nowTime + " " + start
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
formattedTime = dateFormatter.date(from: concat)!
}
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
timeOutPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 5, to: formattedTime)
logoutTextField.text = formatter.string(from: sender.date)
}

match datePicker date and timer with users Date and Time (swift3)

My code below creates a date picker and has it select a date and time. All I want to do is when the date picker's date and time match the user's phone's date and time is to print the line "cool". That's it. I commented the line that is causing me problems.
import UIKit
var dateFormatter : DateFormatter!
let datePicker2 = UIDatePicker();
let date = Date()
class ViewController: UIViewController {
#IBOutlet var dateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let datePicker : UIDatePicker = UIDatePicker(frame: CGRect(x: 0,y: 330,width: self.view.frame.size.width,height: 220))
datePicker.datePickerMode = UIDatePickerMode.dateAndTime
self.view.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(ViewController.change(_:)), for: UIControlEvents.valueChanged)
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd hh:mm"
}
#IBAction func change(_ sender : UIDatePicker)
{
dateLabel.text = dateFormatter.string(from: sender.date)
///print cool line; what I have does not work
if dateLabel.text == String(describing: date){
print("cool")
}
}
}
Your primary issue is how you compare the two dates. You should be using the same date formatter to convert both Date instances to strings in the same format. Then you can compare the two strings.
#IBAction func change(_ sender : UIDatePicker)
{
let pickerString = dateFormatter.string(from: sender.date)
let nowString = dateFormatter.string(from: Date())
dateLabel.text = pickerString
if pickerString == nowString {
print("cool")
}
}
You are also using the wrong format. You need "yyyy-MM-dd HH:mm". YYYY is slightly different. You always want yyyy unless you have a clearly understood and specific need to use YYYY. And for the hour you want HH instead of hh. HH is a 24-hour hour while hh is a 12-hour hour. Only use hh is you also use a (for AM/PM).
And your properties should be inside the class, not outside.
Move datePicker2 inside the class.
date is now obsolete based on my answer so you can remove it completely.
dateFormatter should also be moved inside the class.

How to convert string in text field to NSDate type?

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 {
}

Resources