1

I´m assembling an application with regular web updates. Every update leaves an unix time stamp. Now i try to create an editor, which shows the elapsed time since last update. I´m convering the unix time stamp with this code:

import Cocoa

struct UnixConverter {

    static func converUnix(_ timestamp: Int) -> NSDate? {

        let date = NSDate(timeIntervalSince1970: TimeInterval(timestamp))

        return date
    }
} 

Now I´m getting a time in this format: "2017-06-16 17:47:45 +0000" The following function gives me a reals time push update inside a NSTextFieldCell:

import Cocoa

 class ViewController: NSViewController {

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        // This function pushes the time NSTextFieldCell
        timer = Timer.scheduledTimer(timeInterval: 1.0,
                                        target: self, s
                                        elector: #selector(tick),
                                        userInfo: nil,
                                        repeats: true)
    }


    // This is the NSTextFieldCell formatter/ receiving container
    @objc func tick() {
        timerTextField.stringValue = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .medium)
    }
 }

Now "all" I would have to do, is to make a subtraction to get the difference. At this point I must confess I don´t have any idea how to do this. After that the time difference has to be pushed inside the NSTextFieldCell. I would be very glad if someone could give me a hint how to do it.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Josch Hazard
  • 323
  • 3
  • 20
  • Check this answer https://stackoverflow.com/a/40117486/4449018 – srvv Jun 16 '17 at 18:28
  • ramains the question how to push a stringvalue in realtime in a NSTextFieldCell.? – Josch Hazard Jun 16 '17 at 18:33
  • And, in case of you proposed answer, i´m getting the timevalue only when the function is executed. – Josch Hazard Jun 16 '17 at 18:35
  • 1
    Completely unrelated, but I'd suggest not using `NSDate` anymore. Consider using `Date`. – Rob Jun 16 '17 at 19:16
  • 1
    Rather than doing "subtraction" to get the difference, consider using [`DateComponentsFormatter`](https://developer.apple.com/documentation/foundation/datecomponentsformatter) to show the amount of time that has elapsed since a particular date. [This is iOS answer](https://stackoverflow.com/a/44556477/1271826), but the idea is the same in macOS. This formatter is really powerful, allowing not only the `0:00:00` format in that answer, but all sorts of `.unitsStyle` options, such as `.full` that generates localized strings, etc. – Rob Jun 16 '17 at 19:20

0 Answers0