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");
}
In the Format Cells window, go to the Number tab, select Custom from the Category list, and enter h:mm:ss. 000 in the Type text box. As a result, all of the time values are displayed with milliseconds as decimals.
To get the milliseconds only of the current time, we use the "Millisecond" property of the DateTime class in C#. We use the "Millisecond" property with the object of DateTime class which should be initialized with the current date-time i.e. "Now".
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 property var 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:
protected void Page_Load(object sender, EventArgs e)
{
var timer = System.Diagnostics.Stopwatch.StartNew();
// sleep for 2.5s
Thread.Sleep(2500);
timer.Stop();
var elapsed = timer.Elapsed;
Result.Text = elapsed.ToString("mm':'ss':'fff");
}
Hope that helps!
James
The doc says: "fff" gives you:
The milliseconds in a date and time value.
You're using "ff" which gives you:
The hundredths of a second in a date and time value.
So, change your code to:
duration.ToString("mm':'ss':'fff");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With