How show minutes and seconds with Stopwatch()

前端 未结 7 468
北荒
北荒 2021-02-01 12:20

I need to show also the minutes, actually I use this code for show the seconds, but also need the minutes

TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine(\"F         


        
相关标签:
7条回答
  • 2021-02-01 13:23

    The TimeSpan.ToString() method in .NET 4.0 has an overload that lets you specify the format.

    To display minutes and seconds:

    TimeSpan elapsed = GetElapsedTime(); // however you get the amount of time elapsed
    string tsOut = elapsed.ToString(@"m\:ss");
    

    To include the milliseconds, you would write:

    string tsOut = elapsed.ToString(@"m\:ss\.ff");
    

    Note, however, that this won't do what you expect if the total timespan is more than 60 minutes. The "minutes" value displayed will be elapsed.Minutes, which is basically the same as ((int)elapsed.TotalMinutes) % 60). So if the total time was 70 minutes, the above will show 10:00.

    If you want to show the total minutes and seconds reliably, you have to do the math yourself.

    int minutes = (int)elapsed.TotalMinutes;
    double fsec = 60 * (elapsed.TotalMinutes - minutes);
    int sec = (int)fsec;
    int ms = 1000 * (fsec - sec);
    string tsOut = String.Format("{0}:{1:D2}.{2}", minutes, sec, ms);
    
    0 讨论(0)
提交回复
热议问题