尝试从 date/time 中减去一个数字并在文本字段中设置该值时遇到问题

Having trouble trying to subtract a number from a date/time and setting that value in a textField

我正在开发一个具有开始时间、结束时间和持续时间的应用程序。用户可以通过单击按钮设置结束时间,并将值设置为 "now",格式为 12:02:03 PM。然后我希望能够以分钟为单位输入持续时间,比如 20 分钟。

我的一切都在工作,我可以实时读取持续时间以及查看当前时间。问题是当我尝试创建一个函数来从 endTime 中减去持续时间时。我似乎无法获得正确的语法或格式。

我已经做了很多搜索来寻找这方面的例子。这是我到目前为止遇到的情况。

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
}

controlTextDidChange 函数正在监视 durationTextField,我能够打印以控制输入。然后我希望能够使用 durationTextField 值 运行 timeString 函数并将其从 endTime 中减去,然后将该值设置为 startTime

有一件事很奇怪 Xcode 告诉我:

Result of call to 'addingTimeInterval' is unused

这并不奇怪,警告告诉您 addingTimeInterval 创建并 returns 一个新日期。

只需使用调用'addingTimeInterval'

的结果

Date 转换为 String 再转换回 Date 是没有意义的。

func timeString(time: TimeInterval) {
    formatter.dateFormat = "hh:mm:ss a"
    let newDate = Date().addingTimeInterval(-time)
    let wtf = formatter.string(from:newDate)
    startTime.stringValue = wtf
}

您步数过多。只需创建一个 Date,即距 "now" time 秒。然后将 Date 转换为 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
}

我假设您希望 startDate 现在 time 之前

在 vadian 和 rmaddy 的帮助下,我成功了。

这是我的工作代码

func timeString(time: TimeInterval) {
    formatter.dateFormat = "hh:mm a"
    let endTimeValue = formatter.date(from: endTime.stringValue)
    let newTime = endTimeValue!.addingTimeInterval(-time * 60)
    let newtimeString = formatter.string(from:newTime)
    startTime.stringValue = newtimeString
}