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
In C#, the multiplication symbol used is the asterisk (*), so if you want to multiply a number by another number, you simply need to place the asterisk between them: a = 6; b = 2; Console. WriteLine(a * b);
TimeSpan(Int32, Int32, Int32, Int32) Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, and seconds. TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, seconds, and milliseconds.
the period of time between two events or during which an event continues. a timespan of ten to fifteen years.
TimeSpan (amount of time) is a new data type that can be used to store information about an elapsed time period or a time span. For example, the value in the picture (148:05:36.254) consists of 148 hours, 5 minutes, 36 seconds, and 254 milliseconds.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With