How to send Date and Time separately to backend in swift? - swift

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

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

How to use the time of datePicker only after clicking at Save Button

I am trying to use the hour and minutes of the date picker and add a notification with it. It is working now when the user immeadiatly chooses the hour and minutes from the DatePicker. My problem is that I only wanna create the notification when the user clicks at a Button Save, not when changing the value of the picker. How do I do that?
#objc func printMedHour(sender: UIDatePicker) {
let date = DateFormatter()
date.timeStyle = .short
let dateString = date.string(from: datePicker.date)
let dateAsString = (dateString)//"1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let dates = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: dates!)
//print(dateString)
print(Date24)
let hour = Date24.prefix(2)
let minutes = Date24.suffix(2)
print(hour)
print(minutes)
let content = UNMutableNotificationContent()
content.title = "Time to take your med"
content.body = "Don't forget"
var dateComponent = DateComponents()
dateComponent.calendar = Calendar.current
let hourString = (hour)
let hourInt = Int(hourString)
print(hourInt)
let minuteString = (minutes)
let minuteInt = Int(minuteString)
print(minuteInt)
//dateComponent.weekday = 7 //Saturday
dateComponent.hour = (hourInt) as? Int //Hour
dateComponent.minute = (minuteInt) as! Int //Minute
//Trigger:
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: {(error) in
if error != nil {
print("Error")
}
})
self.reminderTextField.text = dateString
view.endEditing(true)
}
My Button is the following:
let saveButton: UIButton = {
let button = UIButton()
button.setTitle("Save", for: .normal)
button.backgroundColor = UIColor.rgb(red: 40, green: 40, blue: 40)
button.contentMode = .center
button.titleLabel?.textColor = .white
button.titleLabel?.font = UIFont(name: "Verdana", size: 20)
button.addTarget(self, action: #selector(saveUserSettings), for: .touchUpInside)
button.isOpaque = true
button.layer.opacity = 0.9
button.addTarget(self, action: #selector(AddMedViewController.printMedHour(sender:)), for: UIControl.Event.valueChanged)
return button
}()
When adding the target to the date picker, the notification is not created.
What I am doing wrong?
Thanks!

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

Swift countdown timer- displays days hours seconds remaining

Hello I am very new to swift and I was trying to create an app that counts down to an event on a specific date. I want it to show the number of days hours and seconds left until the specified date but I cannot figure out how to do this.
Please help!
Swift 4
var releaseDate: NSDate?
var countdownTimer = Timer()
func startTimer() {
let releaseDateString = "2018-09-16 08:00:00"
let releaseDateFormatter = DateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.date(from: releaseDateString)! as NSDate
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
#objc func updateTime() {
let currentDate = Date()
let calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: releaseDate! as Date)
let countdown = "Days \(diffDateComponents.day ?? 0), Hours \(diffDateComponents.hour ?? 0), Minutes \(diffDateComponents.minute ?? 0), Seconds \(diffDateComponents.second ?? 0)"
print(countdown)
}
This works like a charm:
var releaseDate: NSDate?
override func viewDidLoad() {
super.viewDidLoad()
let releaseDateString = "2016-03-02 22:00:00"
let releaseDateFormatter = NSDateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.dateFromString(releaseDateString)!
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDownDate", userInfo: nil, repeats: true)
}
func countDownDate() {
let currentDate = NSDate()
let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: currentDate, toDate: releaseDate!, options: .MatchFirst)
let countdown = "Months: \(diffDateComponents.month), Days: \(diffDateComponents.day), Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
print(countdown)
}
Swift 3
var releaseDate: Date?
override func viewDidLoad() {
super.viewDidLoad()
let releaseDateFormatter = DateFormatter()
releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
releaseDate = releaseDateFormatter.date(from:releaseDateString!)!
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.countDownDate), userInfo: nil, repeats: true)
}
func countDownDate() {
let date = Date()
let calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: date, to: releaseDate!)
let countdown = "Days \(diffDateComponents.day), Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
print(countdown)
}
This is what I had to do for my app.
import UIKit
import Foundation
var timer = Timer()
var currentTime = Date()
var compareTime = Date().addingTimeInterval(-21600)
func setupButtonTitle()
{
if UserDefaults.standard.object(forKey: "count6") == nil
{
button.setTitle("PRESS", for: .normal)
button.backgroundColor = .green
}
else
{
button.setTitle("PRESS" + "\nIN " + "\(startTimer()))" , for: .normal)
}
button.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
}
func startTimer()
{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(sixHourCountdown), userInfo: nil, repeats: true)
}
#objc func sixHourCountdown()
{
let timeStarted = UserDefaults.standard.object(forKey: "count6")
let timeStart = timeStarted as! Date
let diffComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: compareTime, to: timeStart)
let hour = diffComponents.hour!
let minute = diffComponents.minute!
let second = diffComponents.second!
let timeRemaining = String(format: "%02d:%02d:%02d", hour, minute, second)
compareTime += 1
if hour == 0 && minute == 0 && second == 0 || timeStart < compareTime
{
button.setTitle("PRESS", for: .normal)
button.backgroundColor = .green
timer.invalidate()
}
else
{
button.setTitle("PRESS IN" + "\n\(timeRemaining)", for: .normal)
}
}
#objc func buttonTap()
{
if button.currentTitle != "PRESS"
{
button.backgroundColor = .red
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute:
{
button.backgroundColor = .yellow
})
}
if button.currentTitle == "PRESS" && button.backgroundColor == .green
{
UserDefaults.standard.set(currentTime, forKey: "count6")
let otherVC = OTHERVC()
self.navigationController?.pushViewController(otherVC, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupButtonTitle()