Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display duration in milliseconds

Tags:

c#

c#-4.0

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");
}
like image 767
fn27 Avatar asked Mar 05 '12 11:03

fn27


People also ask

How do you show time in milliseconds?

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.

How do I get milliseconds in C#?

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".


2 Answers

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

like image 116
james lewis Avatar answered Sep 19 '22 20:09

james lewis


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");
like image 32
Candide Avatar answered Sep 20 '22 20:09

Candide