Swift获取目标字符串日期上剩余的时间

The current date time today was May 9, 2020 10:03 PM, and I have a target string date with the value of 2020-05-09 22:07:30 with the format of yyyy-MM-dd HH:mm:ss.

How can I get the remaining date from that 2 date and print the value with the string of 04:30 as the range of those 2 dates are 4 minutes and 30 seconds

我只能将毫秒转换为时间格式,例如

func msToTime(ms: Int) {
    let seconds = ms % 60
    let minutes = ms / 60000

    return String(format: "%0.2d:%0.2d",minutes,seconds)
}

Output 04:30

但是我不知道如何获取从今天的日期时间到目标日期时间的毫秒数范围。 或者,如果还有其他更简单的方法呢?

评论
爱上ni
爱上ni

一种简单的方法,无需任何形式的计算:

let d1 = Date()
let s = "2020-05-09 22:07:30"
let f = DateFormatter()
f.dateFormat = "yyyy-MM-dd HH:mm:ss"
f.timeZone = TimeZone.current // or whatever
if let d2 = f.date(from: s) {
    let f = DateComponentsFormatter()
    f.unitsStyle = .positional
    let result = f.string(from: d1, to: d2)
}

If you don't like the resulting string format of result, you can eliminate pieces of it. — However, note that this works only because no full days are involved. It isn't clear what the range of possible inputs might be or what the desired output would be if the second date were three months into the future, for example.

点赞
评论