I have a Current, Start Date, and End Date. How can I convert these dates to elapsed and remaining time format using Swift?
The format needed is 00:00:00 (hours: minutes: seconds)
Currently, I get elapsed and remaining strings using the below code.
The code returns incorrectly to the Time I see in the Simulator.
Example: If the simulator time changes to 2:45 pm My elapsed time's second is ahead (10s) of the actual seconds shown. And the remaining seconds shows ahead for (9s)
I am getting like this
elapsed = 01:30:10, rem = 12:30:09
Can you help me fix the code or a simpler way to get the format I want correctly?
Code:
{
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)!
}
CodePudding user response:
There is an API for that: 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)
CodePudding user response:
It actually works with the exact date and time that you are creating with that current date constant. And if you are changing string to date from dateformatter then you need to check if you are getting the exact value there after changing.