How do I multiply a TimeSpan object in C#? Assuming the variable duration
is a TimeSpan, I would like, for example
duration*5
But that gives me an error "operator * cannot be applied to types TimeSpan and int". Here's my current workaround
duration+duration+duration+duration+duration
But this doesn't extend to non-integer multiples, eg. duration * 3.5
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.
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);
You can use the internal data of TimeSpan, namely ticks.
TimeSpan day = TimeSpan.FromDays(1);
TimeSpan week = TimeSpan.FromTicks(day.Ticks * 7);
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);
You need to specify which member it is you want to multiply by 5 -> TimeSpan.TotalMinutes * 5
The problem here is that you want to multiply timespan. The simplest workaround is to use ticks. eg.
var ticks = TimeSpan.FromMinutes(1).Ticks;
var newTimeSpan = TimeSpan.FromTicks(ticks*5);
来源:https://stackoverflow.com/questions/9909086/multiply-timespan-in-net