Set Time Default in UIDatePicker - swift

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

Related

how to call function in Extension in swift?

I'm making an app but I'm confused about how to call the function in the extension file.
This is the code that I'm trying to call the function from the extension.
import UIKit
class RecipeTableViewCell: UITableViewCell {
#IBOutlet weak var commnetLabel: UILabel!
#IBOutlet weak var recipeImageView: UIImageView!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var recipeTypeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureView(recipe: RecipeData){
commnetLabel.text = recipe.comment
recipeImageView.setImage(imageUrl: recipe.imageUrl)
// dateLabel.text = recipe.recordedAt => get something like 2020-10-01 11:08:42
dateLabel.text = setTemplate(strDate: recipe.recordedAt)
recipeTypeLabel.text = recipe.recipeType
}
}
In the configureView function, I used to write dateLabel.text = recipe.recordedAtto show the date to the app. I'm now trying to change how it is displayed, so I created an extension.
import Foundation
extension DateFormatter {
func setTemplate (strDate: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
let result = dateFormatter.string(from: Date())
return result
}
}
I thought writing dateLabel.text = setTemplate(strDate: recipe.recordedAt) in configureView function enables to call setTemplate function and change my dateLabel's text. However, currently I'm getting
Use of unresolved identifier 'setTemplate'
and I'm confused about why and how to access to setTemplate function.
Could anyone tell me why I'm getting the error and what I'm doing wrong?
You probably meant to extend RecipeTableViewCell, not DateFormatter.
extension RecipeTableViewCell {
func setTemplate(strDate: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
let result = dateFormatter.string(from: Date())
return result
}
}
If you extend DateFormatter, the function setTemplate is added to the class DateFormatter -- you can't access it from RecipeTableViewCell. But if you really wanted to extend DateFormatter, you could do it like this:
extension DateFormatter {
func setTemplate(strDate: String) -> String {
self.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
let result = self.string(from: Date())
return result
}
}
/// usage:
let formatter = DateFormatter()
dateLabel.text = formatter.setTemplate(strDate: recipe.recordedAt)
Extending DateFormatter directly lets you access setTemplate from anywhere (not just RecipeTableViewCell), so you might want to do this.
Your function is correct but you just need to make it static. Just tested in PLayground and it worked.
extension DateFormatter {
static func setTemplate (strDate: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
let result = dateFormatter.string(from: Date())
return result
}
}

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()
}

How can capture a date from UIDatePicker to an outside variable

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)!
}

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