Home » c# » Multiply TimeSpan in .NET

Multiply TimeSpan in .NET

Posted by: admin November 30, 2017 Leave a comment

Questions:

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

Answers:

From this article

TimeSpan duration = TimeSpan.FromMinutes(1);
duration = TimeSpan.FromTicks(duration.Ticks * 12);
Console.WriteLine(duration);     

Questions:
Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

You can use the internal data of TimeSpan, namely ticks.

TimeSpan day = TimeSpan.FromDays(1);
TimeSpan week = TimeSpan.FromTicks(day.Ticks * 7);

Questions:
Answers:

Use ticks:

http://www.personal.psu.edu/wbk2/blogs/personal_blog/dotnet-stuff-timespan-multiplication-and-division.html

Questions:
Answers:

You need to specify which member it is you want to multiply by 5 -> TimeSpan.TotalMinutes * 5

Questions:
Answers:

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