I have a timer that runs on the website. It will retrieve a timespan of how long a user has until their order expires. For the most part this works fine, the server will return the initial time remaining and the javascript will do the countdown. So it displays
2:30 2:29 2:28
Then for some reason, on some of the page loads (seems to happen when the timer has less than 60 seconds remaining), the formatting turns to
-1:0-45 -1:0-46 -1:0-47
This is the code responsible for formatting the timespan:
<%= (TimeRemaining.TotalMinutes - 1).ToString("N0") %>:<%= TimeRemaining.Seconds.ToString("N0").PadLeft(2,'0') %>
I’ve also just tried the following with the same result.
<%= String.Format("{0:0}:{1:00}", TimeRemaining.TotalMinutes-1, TimeRemaining.Seconds)%>
I also have a check on the TimeRemaining, if the TotalSeconds is <= 0, then it just returns a new TimeSpan(0), so it should never be going negative. It’s not the javascript thats screwing up the countdown, because I can disable it and still see the messed up formatted time.
Is there a better/cleaner way to do this?
One error I can see is that you shouldn’t be subtracting one here:
If there is less than thirty seconds remaining and you subtract one minute you will get a negative number.
Result:
Instead you should round this number down to an integer (also called truncation). You can do this with Math.Floor, but it is also possible to just cast the number to an integer to achieve the same effect:
As for the seconds, I don’t know why that is going wrong. I assume it is because your time remaining can in fact go negative. The error seems to not be in the code you posted.