How can capture a date from UIDatePicker to an outside variable - swift

Im just trying to extract a date to a variable to be used somewhere else and to have that variable change everytime the value of the Picker changes.
#IBAction func datePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
var DateString = dateFormatter.string(from: sender.date)
return
}
Im sure its simple but Im a newbie.
Thank you

Try this
make an extension on Date
extension Date {
func convertDateToString(format : String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
in your VC
let dateFormat = "yyyy/MM/dd"
var currentDate = Date().convertDateToString(format: dateFormat) // to get current date
#IBAction func datePicker(_ sender: UIDatePicker) {
currentDate = sender.date.convertDateToString(format: dateFormat)
}

Use a property observer. It's called whenever the value changes.
var selectedDate : Date = Date() {
didSet {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy/MM/dd"
dateDisplay.text = dateFormatter.string(from: selectedDate)
}
}
#IBAction func datePicker(_ sender: UIDatePicker) {
selectedDate = sender.date
}

Declare it inside the vc
var currentDate = ""
#IBAction func datePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
currentDate = dateFormatter.string(from: sender.date)!
}

Related

Printing a timestamp to a label from a button IB Function in Xcode (Swift)

I want to create a time stamp thats triggered to the current time when a button is pressed in one view controller and have it print to a label in another view controller.
Im using Xcode 11 and the most recent version of swift.
I Guess this is the function i have so far but dont know how to implement it to the button or the label I want it printed to:
func getDateDayAndTime(timestamp: NSNumber) -> String {
let date = Date(timeIntervalSince1970: Double(truncating: timestamp)/1000)
let calendar = Calendar.current
if calendar.isDateInToday(date) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "hh:mm a"
let time = dateFormatter.string(from: date)
return time
}else if calendar.isDateInYesterday(date) {
return "Yesterday"
}
else if calendar.isDateInWeekend(date) {
let component = calendar.component(Calendar.Component.weekday, from: date)
return self.getDay(value: component)
} else {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "dd/MM/YY"
let time = dateFormatter.string(from: date)
return time
}
}
We can send the timestamp value from ViewController to SecondViewController as shown below,
import UIKit
class ViewController: UIViewController {
#IBAction func getTimeStampButtonAction(_ sender: Any) {
let timestampVal = NSDate().timeIntervalSince1970
let myTimeInterval = TimeInterval(timestampVal)
let timeStamp = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
let timeStampString = stringFromDate(timeStamp as Date)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let homeView = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
homeView.timeStamp = timeStampString
self.navigationController?.pushViewController(homeView, animated: true)
}
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var TimeStampLabel: UILabel!
var timeStamp: String!
override func viewDidLoad() {
super.viewDidLoad()
TimeStampLabel.text = timeStamp
}
}
Function that returns current time:
func getTodayString() -> String{
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let second = components.second
let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) + " " + String(hour!) + ":" + String(minute!) + ":" + String(second!)
return today_string
}
Button pressed:
#IBAction func buttonPressed(_ sender: Any) {
yourLabel.text = getTodayString()
}

Set Time Default in UIDatePicker

I'm trying to populate a pickerView with a default value (String). Currently I'm able to capture it's value as a time after the user interacts with it, however I'm not able to set the time value before it becomes visible to the user.
I've tried
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
however that errors "Value of type '(UIDatePicker) -> ()' has no member 'setDate'"
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
//my attempt at passing in a string
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
tempTime = (dateFormatter.string(from: sender.date))//successfully captures the user's input value
}
Here's the function that launches the xib (containing the timePicker)
func showSomeDialogue() {
let newVC = SomeViewContoller(nibName: "SomeViewController", bundle: nil)
let popup = PopupDialog(viewController: newVC,
buttonAlignment: .horizontal,
transitionStyle: .bounceUp,
tapGestureDismissal: true,
panGestureDismissal: false)
present(popup, animated: true, completion: nil)
newVC.someDelegate = self as SomeDelegate
}
The xib's class
import UIKit
protocol MealDelegate {
func didCreateMeal(mealTime: String)
}
class SomeViewContoller: UIViewController {
var someDelegate: SomeDelegate!
var tempTime = ""
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
tempTime = (dateFormatter.string(from: sender.date))
}
#IBAction func someSaveBtn(_ sender: UIButton) {
mealDelegate.didCreateMeal(mealTime: tempTime)
self.dismiss(animated: true, completion: nil)
}
}
Add following to your view controller class:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "09:00 AM")
timePicker.date = date
Add the following to your SomeViewController class:
//MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "10:57 PM")
//or whatever date you want to display as default
timePicker.setDate(date, animated: true)
}
Try this,
#IBAction func timePicker(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .dateAndTime
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleTimePicker(sender:)), for: .valueChanged)
}
#objc func handleTimePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "
tempTime = dateFormatter.string(from: sender.date)
// view.endEditing(true)
}

Cannot convert value of type 'String' to expected argument type 'TimeInterval' (aka 'Double')

I am formatting time that is being passed in. I am getting this error, and I'm trying to figure out what's happening here with it. I'm using the most up to date version of Xcode (v. 8) and am programming in Swift 3. What this error means and how to fix it?
I'm piecing in parts of the code that are relevant to the question so it's not a overload of information here.
var date: String {
if _date == nil {
_date = ""
}
return _date
}
init(weatherDict: Dictionary<String, AnyObject>){
if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject>
{
if let min = temp["min"] as? Double{
self._lowTemp = ktof(kelvins: min)
}
if let max = temp["max"] as? Double{
self._highTemp = ktof(kelvins: max)
}
}
let unixConvertedDate = Date(timeIntervalSince1970: date)
if let date = weatherDict["dt"] as? Double {
let unixConvertedDate = Date(timeIntervalSince1970: date)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
//dateFormatter.dateFormat = "EEEE"
dateFormatter.dateStyle = .none
self._date = unixConvertedDate.dayoftheWeek()
}
}
and then outside of the class, which all the above code is inside of, I have this.
extension Date {
func dayoftheWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
}
if let date = weatherDict["dt"] as? Double {
let unixConvertedDate = Date(timeIntervalSince1970: date)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.dateFormat = "EEEE"
dateFormatter.timeStyle = .long
self._date = "\(unixConvertedDate)"
}
}
}
extension Date {
func dayOfTheWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
}

UIPickerView selected time to run code

I have added in a UIPickerView and currently have it store the selected time as a string. I want the app to carry out a simple line of code when the time that was selected on the pickerview is the time in the real world. Here is the code that I have added.
For the Clock, used to find the real world time:
let clockString: String = formatADate()
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm:ss a"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
Here is the code for the UIPickerView:
#IBOutlet var dateTimeDisplay: UILabel!
#IBOutlet var datePicker: UIDatePicker!
#IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
}
func setDateAndTime() {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
dateTimeDisplay.text = str
}
And here is what I want to happen when the selected time and the real world time match up:
takePhoto = true
When the pick date the start one timer function
call the function in picker
var timercount = Timer()
viewdidload()
{
timercount = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
}
Func Check()
{
let nowdate = NSDate()//two date declare global Var
let date2 = datePicker?.date //chek the Time How Much Time Remain
let elapsed = date2?.timeIntervalSince(nowdate as Date)
if Int(elapsed!) == 0
{
takePhoto = true
}
}

How to convert date picker value into String in swift 3.0?

How to convert date picker value into String type in Swift 3.0 ?
Right now I have managed to create date picker but the value that appear in textfield is today's date which is 2/8/17, m/d/yy format.
My goal is to convert m/d/yy into String and the date value will be 2017-02-08, yyyy/mm/dd format
The code as below.
Date.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var dateTxt: UITextField!
let datepicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
displayDate()
}
func displayDate(){
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePick))
toolbar.setItems([doneBtn], animated: false)
dateTxt.inputAccessoryView = toolbar
dateTxt.inputView = datepicker
}
func donePick(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateTxt.text = dateFormatter.string(from: datepicker.date)
self.view.endEditing(true)
}
}
Can anyone help ?
Thanks.
For that you need to set dateFormat property of DateFormatter not the dateStyle and timeStyle.
func donePick(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateTxt.text = dateFormatter.string(from: datepicker.date)
self.view.endEditing(true)
}