Search code examples
iosswiftdatetimetimestampuidatepicker

How to read values from UIDatePicker:Time and convert it into timestamp?


This is how my picker for time looks like:
Time picker

How can I read what time user picked and convert it into timestamp so I can be able to do some calculations with it?


Solution

  • 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