Home > Back-end >  TimeSpan and ToString()
TimeSpan and ToString()

Time:01-22

I want to display minutes, seconds, and milliseconds saved in TimeSpan. It should look like this:

var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
        
var d = d1 - d2;
Console.WriteLine(d.ToString(@"mm\:ss\:fff"));

But it returns 47:30:000 which is only partially true, because it ignored one hour. I want it to be converted into minutes, not ignored.

CodePudding user response:

I think you need TimeSpan.TotalMinutes.

https://learn.microsoft.com/en-us/dotnet/api/system.timespan.totalminutes?view=net-7.0

In your case it could be:

Console.WriteLine($@"{(int)d.TotalMinutes}:{d:ss\:fff}");

CodePudding user response:

TimeSpan Struct has a property for getting the total number of minutes contained in it, as a double value: TimeSpan.TotalMinutes Property.

Note that if your TimeSpan's duration is not in integral minutes you will get a fraction part:

var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
var d = d1 - d2;
Console.WriteLine(d.TotalMinutes);

Output:

107.5

Note that TimeSpan has similar properties for TotalDays, TotalHours, TotalSeconds, TotalMilliseconds.


Update:
Based on the comments below, here's a solution that prints in a format splitting minutes, seconds and milliseconds:

var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
var d = d1 - d2;
var totalMin = d.TotalMinutes;
int totalMinInt = (int)totalMin;
double totalMinFrac = totalMin - totalMinInt;
Console.WriteLine(totalMinInt.ToString()   ":"   
                  TimeSpan.FromMinutes(totalMinFrac).ToString(@"ss\:fff"));

Output:

107:30:000
  • Related