Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply TimeSpan in .NET

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

like image 688
Colonel Panic Avatar asked Mar 28 '12 13:03

Colonel Panic


People also ask

How do you multiply numbers in C#?

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);

What is TimeSpan in asp net?

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.

What is TimeSpan time?

the period of time between two events or during which an event continues. a timespan of ten to fifteen years.

What is data type TimeSpan?

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.


2 Answers

From this article

TimeSpan duration = TimeSpan.FromMinutes(1); duration = TimeSpan.FromTicks(duration.Ticks * 12); Console.WriteLine(duration);      
like image 74
Justin Pihony Avatar answered Oct 14 '22 14:10

Justin Pihony


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.

like image 43
Stephen Hewlett Avatar answered Oct 14 '22 16:10

Stephen Hewlett