Multiply TimeSpan in .NET
From this article
TimeSpan duration = TimeSpan.FromMinutes(1);
duration = TimeSpan.FromTicks(duration.Ticks * 12);
Console.WriteLine(duration);
For those wishing to copy and paste:
namespace Utility
{
public static class TimeSpanExtension
{
/// <summary>
/// Multiplies a timespan by an integer value
/// </summary>
public static TimeSpan Multiply(this TimeSpan multiplicand, int multiplier)
{
return TimeSpan.FromTicks(multiplicand.Ticks * multiplier);
}
/// <summary>
/// Multiplies a timespan by a double value
/// </summary>
public static TimeSpan Multiply(this TimeSpan multiplicand, double multiplier)
{
return TimeSpan.FromTicks((long)(multiplicand.Ticks * multiplier));
}
}
}
Example Usage:
using Utility;
private static void Example()
{
TimeSpan t = TimeSpan.FromSeconds(30).Multiply(5);
}
t
will end up as 150 seconds.
TimeSpan.Multiply
has arrived in .NET Core, and looks like it will arrive in .NET Standard 2.1:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.op_multiply?view=netstandard-2.1
var result = 3.0 * TimeSpan.FromSeconds(3);
The TimeSpan
structure does not provide an overload for the *
operator, so you have to do this yourself:
var result = TimeSpan.FromTicks(duration.Ticks * 5);