-2

Assuming I have a TimeSpan that is equal to 07:10:30, I can use the following code to strip the seconds from it:

myTimeSpan = new TimeSpan(myTimeSpan.Hours, myTimeSpan.Minutes, 0)

Is this appropriate, or is there a more elegant way to achieve this?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Izacch
  • 383
  • 3
  • 10
  • I think this is very fine approach. – Joelty Nov 08 '21 at 11:01
  • 2
    Do you also want to strip the [`Days`](https://learn.microsoft.com/en-us/dotnet/api/system.timespan.days) component from the `TimeSpan` value? Because that's what your current code does. – Theodor Zoulias Nov 08 '21 at 11:12

2 Answers2

2

I would propose

TimeSpan.FromMinutes((long) myTimeSpan.TotalMinutes)

This removes any time component smaller than one minute, while keeping anything larger, like days, hours etc. Use Math.Round if you want rounding to nearest minute instead of truncating.

JonasH
  • 28,608
  • 2
  • 10
  • 23
1

Make an extension method that rounds towards zero to the nearest TimeSpan.TicksPerMinute.

public static class TimeSpanExtensions
{
    public static TimeSpan WithoutSeconds(this TimeSpan ts)
    {
        const long ps = TimeSpan.TicksPerMinute;
        long roundedTicks = ts.Ticks / ps * ps;
        return new TimeSpan(roundedTicks);
    }
}

Ref: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.ticks?view=net-5.0#System_TimeSpan_Ticks

jdphenix
  • 15,022
  • 3
  • 41
  • 74