UIDatePicker returns current date not selected date
to get change of DatePicker listen to datePickerChanged
datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)
So your cell will be
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("FirstTableViewCell", owner: self, options: nil)?.first as! FirstTableViewCell
// Date & time picker
cell.datePicker.minimumDate = Date()
cell.datePicker.timeZone = TimeZone.current
cell.datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)
// Discover button
cell.discoverButton.addTarget(self, action: #selector(setupDiscoverButton), for: .touchUpInside)
return cell
}
@objc func datePickerChanged(picker: UIDatePicker) {
print(picker.date)
}
UIDatePicker of type Date & Time only returns Date and not Time
You have to set timeStyle
as well, e.g.
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
otherwise you'll get only the "date" part.
How to get hours and minutes from UIDatePicker
UIDatePicker
just give you the selected Date
, if you need the date component based on current calendar, check out the Calendar
and DateComponent
documendation for details.
let now = Date() // your date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: now)
dateComponents.hour
dateComponents.minute
If you need hours
and minutes
for time distance, you need the calculate it manually with your prefer base date.
How to make a DatePicker View show only date and not time
Set the datePickerMode property to UIDatePickerModeDate.
UIDatePicker not showing expected time
As mentioned in the comment by @PJayRushton, you get a UTC date printed.
In order to get your local timezone, you can modify your printing code to something like:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timePicker: UIDatePicker!
@IBAction func startButton(_ sender: UIButton) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "HH:mm" // or whatever other format you want
print(dateFormatter.string(from: timePicker!.date))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
How to read values from UIDatePicker:Time and convert it into timestamp?
So first of all I use a Singelton Class, that's a class that can be init just once. That's why you only can access the DateFormat only with
DateFormat.shared.
So that's for calculation:
import Foundation
class DateFormat {
static let shared = DateFormat()
// Date Formatters
let dateFormatterGetFullTimeAndDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = Locale(identifier: "de_DE") as Locale
print("DATE: \(Date())")
return formatter
}()
let dateFormatterGetOnlyDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE") as Locale
formatter.dateFormat = "yyyy.MM.dd"
return formatter
}()
let dateFormatterGetOnlyTime: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE") as Locale
formatter.dateFormat = "HH:mm"
return formatter
}()
// For output in the right order use this Funktion with extension seeing below:
func revertDateStr(inputDate: Date, outputFormat: Int) -> String {
// outputFormats:
// 0: dd.MM.
// 1: dd.MM.yyyy
// 2: dd.MM.yyyy, HH:mm
// 3: yyyy-MM-dd, HH:mm:ss
// 4: HH:mm
// print("--------------------- FUNC revertDateStr ---------------------")
let strDtm = dateFormatterGet.string(from: inputDate)
// print("inputDate: \(strDtm)")
let strDtmyyyy = strDtm[0..<4]
let strDtmMM = strDtm[5..<7]
let strDtmdd = strDtm[8..<10]
let strDtmHH = strDtm[11..<13]
let strDtmmm = strDtm[14..<16]
var outputStrDtm = ""
if outputFormat == 0 {
outputStrDtm = String(strDtmdd) + "." + String(strDtmMM) + "."
} else if outputFormat == 1 {
outputStrDtm = String(strDtmdd) + "." + String(strDtmMM) + "." + String(strDtmyyyy)
} else if outputFormat == 2 {
outputStrDtm = String(strDtmdd) + "." + String(strDtmMM) + "." + String(strDtmyyyy) + ", " + String(strDtmHH) + ":" + String(strDtmmm)
} else if outputFormat == 3 {
outputStrDtm = String(strDtmyyyy) + "-" + String(strDtmMM) + "-" + String(strDtmdd) + " " + String(strDtmHH) + ":" + String(strDtmmm) + ":" + String("00")
} else if outputFormat == 4 {
outputStrDtm = String(strDtmHH) + ":" + String(strDtmmm)
} else {
print("Choose outputFormat (0...3)")
}
// print("outputString: \(outputStrDtm)")
// print("--------------------- END FUNC revertDateStr ---------------------")
return outputStrDtm
}
extension String {
var length: Int {
return count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
For the datePicker I got this:
datePicker?.minuteInterval = 30
let loc = Locale(identifier: "de_DE")
self.datePicker.locale = loc
self.datePicker.addTarget(self, action: #selector(dateDidChange), for: .valueChanged)
// inside the viewDidLoad
func update(date: Date) {
datePicker.setDate(date, animated: true)
self.indexPath = indexPath
}
// inside the ViewController
@objc func dateDidChange(_ sender: UIDatePicker) {
let datePickerDate = self.datePicker.date
print(datePickerDate)
// or with protocol: delegate?.didChangeDate(date: sender.date)
}
Calculus is done with:
let event = Date()
let laterEvent = event.addingTimeInterval(60 * 60) // One hour added
Related Topics
How to Hide the Navigationbar When Embedding Swiftui in Uikit
Can You Give Uistackview Borders
How to Code Initwithcoder in Swift
iOS Tabbar Item Title Issue in iOS13
How to Create String Split Extension with Regex in Swift
Vapor Toolbox Broken After Upgrading Swift
Adding a View to the Window Hierarchy
How to Install the Alamofire 4.0 in Xcode 8.0
What Are the Precedence Levels of the Swift Operators
Using Swift Library in Xamarin
Swift Anyobject Is Not Convertible to String/Int
How to Add a Watermark to an Image Using This Code
Reversing the Order of a String Value
This Class Is Not Key Value Coding-Compliant for the Key Name.'
How to Remove Numbers from a String in Swift