I want to display duration with milliseconds on a web page. So far I have done this:
I managed to display this output on a label: 00:02:50, but I want to display milliseconds as well, so the result should look like this 00:02:50:000. How do I achieve this?
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
DateTime startTime = DateTime.Now;
// sleep for 2.5s
Thread.Sleep(2500);
DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
Result.Text = duration.ToString("mm':'ss':'ff");
}
First of all, if you’re timing things I would recommend using the StopWatch class as that’s what it’s there for. You can find it in the System.Diagnostics namespace:
System.Diagnostics.Stopwatch.You can instantiate a new one and start measuring the elapsed amount of time with one line of code:
var stop = System.Diagnostics.Stopwatch.StartNew();and then stop the timer with the stop method:stop.Stop();. You can then return the elapsed time using the Elapsed propertyvar elapsed = stop.Elapsed;.Then in order to display the elapsed time with milliseconds you would call the ToString method on the elapsed timespan with the correct parameters.
So putting it all together your code would look like this:
Hope that helps!
James