HI guys I have a date picker calculation app and Im wondering why the selected dates are not prtinting to my text lable. This is the code I have
#IBAction func calculateDays(sender: UIButton) {
if startDateTextField.text == "" || endDateTextField == "" {
let alert2 = UIAlertController(title: "Oops!", message: "Please Select a Start Date!", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
}
else {
let start = String(startDateTextField.text)
let end = String(endDateTextField.text)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
guard let startDate = dateFormatter.dateFromString(start), endDate = dateFormatter.dateFromString(end) else {
// You don't have dates, show error(print("error"), do no nothing - your choice.
return
}
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
let secondNewString = "\(components.day) days"
resultNumberOfDays.text = secondNewString
}
}
If I force unwrap as a test it works using (obviously this isn't safe)
let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!
any ideas on how to get the calculated dates to appear or letting me know what I'm missing here
thanks
Related
I have an alert which has a datepicker in a textfield. I want to reference this textfield to the objc for added properties, how would I be able to do this? I tried to use the following method but it does not work with error 'alert not in scope'.
Alert
#IBAction func info(_ sender: Any) {
let alert9 = UIAlertController (title: "Add Your Info", message: nil, preferredStyle: UIAlertController.Style.alert)
let cancel9 = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alert9.addAction(cancel9)
alert9.addTextField { (textfieldDate: UITextField) in
textfieldDate.placeholder = "Date"
self.datePickerWeight = UIDatePicker()
self.datePickerWeight!.preferredDatePickerStyle = .wheels
self.datePickerWeight?.datePickerMode = .date
self.datePickerWeight?.addTarget(self, action: #selector(ViewController.dateChangedInfo(datePicker:)), for: .valueChanged)
textfieldDate.inputView = self.datePickerInfo
let dateFormatterWeight = DateFormatter()
dateFormatterInfo.dateFormat = "EEEE, MMM d, yyyy"
let todayDateInfo = dateFormatterInfo.string(from: Date.init())
textfieldDate.text = todayDateInfo
}
alert9.addTextField { (textfieldAddInfo: UITextField) in
textfieldAddInfo.placeholder = "Info"
textfieldAddInfo.keyboardType = .decimalPad
}
let ok9 = UIAlertAction(title: "Save", style: UIAlertAction.Style.default) { (action: UIAlertAction) in print("OK")
let textfieldDate = alert9.textFields![0]
let textfieldAddInfo = alert9.textFields![1]
}
dateChangedInfo objC
#objc func dateChangedInfo(datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
let stringDate = dateFormatter.string(from: datePicker.date)
let textfieldDate = alert9.textFields?[0] // Cannot find 'alert9' in scope
self.textfieldDate.text = stringDate
self.fetchData(for: stringDate)
}
Make alert9 an instance variable.
var alert9: UIAlertController?
#IBAction func info(_ sender: Any) {
alert9 = UIAlertController (title: "Add Your Info", message: nil, preferredStyle: UIAlertController.Style.alert)
...
}
fromDateLabel.text getting date and time from datepicker.. which i need to send date and time seperatedly to backend
when i do DateFormatter date is coming correctly but in time, only two digit values are working means time taking 10, 11, 12 O'Clocks. if i take 1,2,3,4,5 its not working
code: here single digit time not working
var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
fromDate = fromDateArr[0]
fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "dd-MM-yyyy"
formateFromdate = inputFormatter.string(from: showDateFrom!)
print("formate from date \(formateFromdate)")
if i formate date and time like below nothing works
let fromDate = fromDateLabel.text!
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm:ssa"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time")
How to send date and time separately to backend.. with 1 to 12hrs time
NOTE: if its 8 o clock then the out put time should be 08:15, not 8:15.. thats the issue.. please help me with code
Design
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var txtdate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.txtdate.setInputViewDatePicker(target: self, selector: #selector(tapDone)) //1
}
#objc func tapDone() {
if let datePicker = self.txtdate.inputView as? UIDatePicker {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yy, hh:mm a"
self.txtdate.text = dateformatter.string(from: datePicker.date)
}
self.txtdate.resignFirstResponder()
}
#IBAction func showClk(_ sender: Any) {
let fromDate = txtdate.text!
print(fromDate)
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm a"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
let formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
let formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time" ,formateFromTime)
}
}
extension UITextField {
func setInputViewDatePicker(target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))//1
datePicker.datePickerMode = .date
self.inputView = datePicker
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func tapCancel() {
self.resignFirstResponder()
}
}
Hi developers im trying to get the date & time from UIDatePicker
my UIDatePicker in on an alert
let myDatePicker: UIDatePicker = UIDatePicker()
let loc = Locale(identifier: "Es_mx")
//myDatePicker.timeZone = NSTimeZone.local
myDatePicker.locale = loc
let date = myDatePicker.date
let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
let year = components.year!
let day = components.day!
let month = components.month!
let hour = components.hour!
let minute = components.minute!
myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
alertController.view.addSubview(myDatePicker)
//let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion:{})
}
already try
let date = myDatePicker.date
let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
let year = components.year!
let day = components.day!
let month = components.month!
let hour = components.hour!
let minute = components.minute!
so when the user press OK button it prints:
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
Print shows current day, month, year, hour and minute
im expect to get what the user selected from UIDatePicker
You initialize a datePicker and get the date from it immediately. This is the problem.
If you want to get the date from the datePicker at the time OK button pressed, you must do this in your closure. Move let date = myDatePicker.date line into your closure, Like so:
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
let date = self.myDatePicker.date
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
}
I am scheduling notification by running the loop in an array.Notification is working fine.But my application is crashing with this error.I know that the OS stops working and os gets rebooted but if i dont call this scheduleNotification function then everything works fine so i know that the error is generation because of this function when i pops to other screen and comes back again my app gets crashg but i dont know why?? please help me out.
func scheduleNotification() {
if dictInfo.object(forKey: "name") !as AnyObject as ? String == "zzz" {
} else {
let calendar = Calendar.current
var calendarComponents = DateComponents()
let strDay = (dictInfo["dd"
as NSString] !as AnyObject).doubleValue
let strMonth = (dictInfo["mm"
as NSString]) !
let dayy = strDay
let monthh = strMonth
calendarComponents.hour = 11
calendarComponents.minute = 04
calendarComponents.day = Int(dayy!) - 2
print(calendarComponents.day)
let df = DateFormatter()
df.dateFormat = "MM" // if you need 3 letter month just use "LLL"
let datee1 = df.date(from: String(describing: monthh))
print(datee1)
let monthh11 = (Calendar.current as NSCalendar).component(.month, from: datee1!)
print(monthh11) // 5
//calendarComponents.year = Int(yearr!)
calendarComponents.month = Int(monthh11)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: calendarComponents.month, day: calendarComponents.day, hour: calendarComponents.hour, minute: calendarComponents.minute)
if# available(iOS 10.0, * ) {
let strName: String = String(describing: dictInfo["name"] !)
let str2: String! = "Today is \(strName)\'s Birthday!"
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Alert Me!"
content.body = str2
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "myCategory"
content.userInfo = ((dictInfo as Any) as ? [AnyHashable: Any]) !
print(content.userInfo.count)
let request = UNNotificationRequest(identifier: strName, content: content, trigger: trigger)
// UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {
(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
} else {
}
}
}
}
MBProgressHUD.hide(
for: self.view, animated: true)
tableVieww.isHidden = false
//self.navigationItem.leftBarButtonItem?.isEnabled = true
}
I want to disable previous time ie before current time from datePicker,As in date picker we can use minimum Date to do this.how could we do the same with time picker.
Here is the Code.`
timePicker = [[UIDatePicker alloc] init];
[self.view addSubview:timePicker];
float tempHeight = timePicker.frame.size.height;
timePicker.frame = CGRectMake(0,200 ,self.view.frame.size.width , tempHeight);
timePicker.hidden = YES;
timePickerFormatter= [[NSDateFormatter alloc]init ];
[timePickerFormatter setDateFormat:#"HH:mm"];
**timePicker.datePickerMode = UIDatePickerModeCountDownTimer;**
timePicker.minuteInterval=15;
`
Thanks in Advance Please suggest me if any way to perform this.
In the default UIDatePicker minimum date can be set and the date property has both date and time values and you can set it there itself
[datePicker setMinimumDate:[NSDate date]];
Here
[NSDate date]
gives current date
So you want to disable previous time from current time.
timePicker.date = [NSDate date];
this sets the time to current time, but i don't think you can disable the previous time.
By This method you can provide alert to user if he/she selected the past time time. Condition is that you already placed a check on minimum date as current day.
func handleTimePicker(sender: UIDatePicker) {
let timeFormatterHour = NSDateFormatter()
let timeFormatterMinutes = NSDateFormatter()
timeFormatterHour.dateFormat = "hh"
timeFormatterMinutes.dateFormat = "mm"
let InputTimeHourString = timeFormatterHour.stringFromDate(sender.date)
let InputTimeMinutesString = timeFormatterMinutes.stringFromDate(sender.date)
let InputTimeHourInt = Int(InputTimeHourString)!
let InputTimeMinutesInt = Int(InputTimeMinutesString)!
let calculatedInputMinutes = (InputTimeHourInt * 60) + InputTimeMinutesInt
let TodayTime = NSDate()
let TodayTimetimeFormatterHour = NSDateFormatter()
let TodayTimetimeFormatterMinutes = NSDateFormatter()
TodayTimetimeFormatterHour.dateFormat = "hh"
TodayTimetimeFormatterMinutes.dateFormat = "mm"
let TodayTimeInputTimeHourString = TodayTimetimeFormatterHour.stringFromDate(TodayTime)
let TodayTimeInputTimeMinutesString = TodayTimetimeFormatterMinutes.stringFromDate(TodayTime)
let TodayTimeInputTimeHourInt = Int(TodayTimeInputTimeHourString)!
let TodayTimeInputTimeMinutesInt = Int(TodayTimeInputTimeMinutesString)!
let TodayTimecalculatedInputMinutes = (TodayTimeInputTimeHourInt * 60) + TodayTimeInputTimeMinutesInt
if TodayTimecalculatedInputMinutes - calculatedInputMinutes < 0
{
let shownDateFormatter = NSDateFormatter()
shownDateFormatter.dateFormat = "hh:mm a"
self.txtTimeEvent.text = shownDateFormatter.stringFromDate(sender.date)
}
else
{
let alertController = UIAlertController(title: "Time Selection Problem", message:
"You cannot select the Past time", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
let shownTime = NSDate()
let shownTimeFormatter = NSDateFormatter()
shownTimeFormatter.dateFormat = "hh:mm a"
self.txtTimeEvent.text = shownTimeFormatter.stringFromDate(shownTime)
}
}
Swift : Add this line in your Picker Function.its Only allow future Time.
My_Pickername.minimumDate = NSDate()
You posted your question two years ago but this may help anyone who will face this issue, I had the same problem today, and here's the solution:
It doesn't really disable previous dates, but if a user selects a previous date, the above function will display an alert and reset the UIDatePicker to the current date :
Swift 4 :
#IBAction func dateChanged(_ sender: Any) {
let dtp = sender as! UIDatePicker
if Date() <= dtp.date {
print ("correct date")
} else {
dtp.date = Date()
let alert = UIAlertController(title: "Error", message: "You have to choose a correct date", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}