Home > OS >  Get minutes and seconds from timespan
Get minutes and seconds from timespan

Time:10-11

I am trying to get the minutes and seconds from a timespan. My two dates for example are 2021-09-08 20:15:46.98Z and 2021-09-08 20:18:32.65Z. What I would like to do is return a decimal value that represents the time difference in minutes and seconds. From this example I would like to return 2.46 rounded (as in 2m 46s), however when I try something like:

TimeSpan span = (end - start); // Where end/start are the example dates
var time = (span.TotalMilliseconds/1000/60);

The result is 2.761166666666667

Is the calculation I am doing incorrect?

CodePudding user response:

Your calculation is correct, You can try this as well (it will give the same result)

var t1 = DateTime.Parse("2021-09-08 20:15:46.98Z");
var t2 = DateTime.Parse("2021-09-08 20:18:32.65Z");
var diff = t2 - t1;
var diffDouble = diff.TotalMinutes; // double 2.7611666666666665
diffDouble = double.Parse($"{diff.TotalMinutes:F2}"); // double 2.76

I would like to return 2.46

var diffStr = $"{diff.Minutes}.{(diff.Milliseconds >= 500 ? diff.Seconds   1 : diff.Seconds)}"; // 2.46
diffDouble = double.Parse(diffStr); // 2.46

CodePudding user response:

If you just want to print it as 2.46, you can do this:

TimeSpan span = (end - start);
Console.WriteLine($"{span.Minutes}.{span.Seconds}");

Alternative:

TimeSpan span = (end - start);
Console.WriteLine("{mm.ss}", span);

More info: https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-6.0

By the way, your math is correct. You're just not getting it as minutes and seconds, but as a decimal number.

CodePudding user response:

Have you tried using the subtract method like this answer?

It looks like you're getting a correct decimal, just not in minutes and seconds since 46 seconds is about 76% of a minute.

CodePudding user response:

The value you get is correct. If you want it in minutes and seconds separately, you can get it like as below

var minutes = Math.Floor(span.TotalSeconds / 60);
var seconds = Math.Ceiling(span.TotalSeconds % 60);

The Ceiling method is used just to round it to the next integer.

CodePudding user response:

DateTime start = DateTime.Parse("2021-09-08 20:15:46.98Z");
DateTime end = DateTime.Parse("2021-09-08 20:18:32.65Z");

TimeSpan timeSpan = end - start;
Console.WriteLine(timeSpan.ToString("mm':'ss"));

Output:

02:45
  •  Tags:  
  • c#
  • Related