Swift中计算当前时间到目标日期的时长差并格式化输出
Hey there! Let's figure out how to solve your problem of calculating the time difference between the current time and your target date, then formatting it into that nice "04:30" string.
Step 1: Parse the target date string into a Date object
First, we need to convert your target date string ("2020-05-09 22:07:30") into a Swift Date instance using DateFormatter. Make sure to set the correct date format and timezone to avoid parsing errors:
let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateFormatter.timeZone = TimeZone.current // Match your device's timezone, adjust if needed guard let targetDate = dateFormatter.date(from: "2020-05-09 22:07:30") else { print("Oops, the target date string is invalid!") return }
Step 2: Calculate the time difference (in milliseconds)
Next, get the current date and compute the time interval between it and the target date. Since timeIntervalSince(_:) returns seconds, we'll multiply by 1000 to get milliseconds:
let currentDate = Date() let timeIntervalInSeconds = targetDate.timeIntervalSince(currentDate) let timeIntervalInMilliseconds = Int(timeIntervalInSeconds * 1000)
Note: If the target date is in the past, this value will be negative. You might want to take the absolute value with abs(timeIntervalInMilliseconds) if you just need the total interval regardless of direction.
Step 3: Fix your msToTime function
Your original function had a small bug—you were treating milliseconds directly as seconds when calculating the remainder. Let's adjust it to first convert milliseconds to total seconds, then compute minutes and seconds:
func msToTime(ms: Int) -> String { let totalSeconds = ms / 1000 let seconds = totalSeconds % 60 let minutes = totalSeconds / 60 return String(format: "%02d:%02d", minutes, seconds) }
Now when you pass in 270000 milliseconds (which is 4 minutes 30 seconds), it'll correctly return "04:30".
Even simpler: Use Calendar to get date components directly
If you don't need to work with milliseconds at all, you can use Calendar to calculate the minute and second components of the time difference directly. This avoids manual math and is more readable:
let calendar = Calendar.current let components = calendar.dateComponents([.minute, .second], from: currentDate, to: targetDate) guard let minutes = components.minute, let seconds = components.second else { print("Failed to calculate time components") return } let formattedTime = String(format: "%02d:%02d", minutes, seconds) print(formattedTime) // Outputs "04:30" when the difference is exactly 4m30s
Either approach will get you the result you need. The Calendar method is great if you want to avoid dealing with raw time intervals, while the millisecond approach works if you need that value for other calculations too.
内容的提问来源于stack exchange,提问作者Dylan

