我有一个"当前"、"开始日期"one_answers"结束日期"。如何使用Swift将这些日期转换为经过时间和剩余时间格式?
所需格式为00:00:00(小时:分钟:秒(
目前,我使用下面的代码获取已用字符串和剩余字符串。
代码错误地返回到我在模拟器中看到的时间。
示例:如果模拟器时间更改为下午2:45我所用时间的秒数比实际显示的秒数提前(10秒(。剩下的几秒钟显示(9秒(
我越来越喜欢这个
经过=01:30:10,rem=12:30:09
你能帮我修复代码吗?或者用一种更简单的方法来正确获得我想要的格式吗?
代码:
{
let currDate = Date();
let startDate = currDate;
let endDate: Date = startDate.addingTimeInterval(TimeInterval(minutes * 60));
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(callback), userInfo: nil, repeats: true);
}
@objc func Callback() {
let time = dateToTimerString(currDate: currDate, startDate: startDate, endDate: endDate );
NSLog( "Elapsed %@, Rem %@", time.elapsed, time.remaining );
}
func dateToTimerString(currDate: Date, startDate: Date, endDate: Date) -> (elapsed: String, remaining: String) {
let elapsedTime: TimeInterval = currDate.timeIntervalSince(startDate);
let remainingTime: TimeInterval = endDate.timeIntervalSince(currDate);
let elapsedString = format(duration: elapsedTime);
let remainingString = format(duration: remainingTime);
return (elapsedString, remainingString);
}
func format(duration: TimeInterval) -> String {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: duration)!
}
有一个API:DateComponentsFormatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad
let elapsedString = formatter.string(from: elapsedTime)
let remainingString = formatter.string(from: remainingTime)
它实际上适用于使用当前日期常量创建的确切日期和时间。若要从日期格式化程序将字符串更改为日期,则需要检查更改后是否得到了确切的值。