I am working on an app that has a startTime, endTime and duration. The user can set the endTime by click a button and it sets the value to "now" in the format 12:02:03 PM. I then want to be able to enter a duration time in minutes, let's say 20 minutes.
I have everything working where I can read the duration in real time as well as see the current time. The issue is when I try to create a function to subtract the duration from the endTime. I cannot seem to get the syntax or the formatting correct.
I've done quite a bit of searching for examples of this. Here is what I came across so far.
How to add minutes to current time in swift
How to subtract date components?
How to get the current time as datetime
func controlTextDidChange(_ obj: Notification) {
let enteredValue = obj.object as! NSTextField
timeString(time: enteredValue.doubleValue)
}
func timeString(time: TimeInterval) {
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date())
let yourDate = formatter.date(from: myString)
formatter.dateFormat = "hh:mm:ss a"
yourDate!.addingTimeInterval(0-time)
let wtf = formatter.string(from: yourDate!)
startTime.stringValue = wtf
}
The controlTextDidChange
function is watching the durationTextField
and I am able to print to console the input. I then want to be able to run the timeString
function with the durationTextField
value and subtract it from the endTime
and then set that value to startTime
.
One thing that is weird is Xcode tells me:
Result of call to 'addingTimeInterval' is unused
You are taking too many steps. Just create a Date
that is time
seconds from "now". Then convert that Date
to a String
.
func timeString(time: TimeInterval) {
let startDate = Date(timeIntervalSinceNow: -time)
formatter.dateFormat = "hh:mm:ss a"
let wtf = formatter.string(from: startDate)
startTime.stringValue = wtf
}
I'm assuming you want startDate
to be time
seconds before now.