bucketman
bucketman

Reputation: 463

Is there a way to get TimeSpan to take two arguments?

The TimeSpan struct takes three or more arguments by default(hours/minutes/seconds etc) but I'm wondering if there is any way to reduce this to two arguments(or even one) to have minutes/seconds or just seconds as arguments.

Upvotes: 0

Views: 315

Answers (3)

Binkan Salaryman
Binkan Salaryman

Reputation: 3048

You have some options here:

  • The TimeSpan.From... methods
  • A factory method:

    public static void MakeSpan(int mins, int secs) {
        return new TimeSpan(0, mins, secs);
    }
    

  • A shortcut-lambda:

    public static void main() {
        Func<int, int, TimeSpan> MakeSpan = (mins, secs) => new TimeSpan(0, mins, secs);
        var span1 = MakeSpan(1, 30);
        var span2 = MakeSpan(2, 05);
        // more to come
    }
    

    Upvotes: 1

  • Tomtom
    Tomtom

    Reputation: 9394

    If you want to only pass seconds or minutes you can use the static-methods:

    TimeSpan timeSpanDays = TimeSpan.FromDays(10);
    TimeSpan timeSpanHours = TimeSpan.FromHours(10);
    TimeSpan timeSpanMilliseconds = TimeSpan.FromMilliseconds(10);
    TimeSpan timeSpanMinutes = TimeSpan.FromMinutes(10);
    TimeSpan timeSpanSeconds = TimeSpan.FromSeconds(10);
    TimeSpan timeSpanTicks = TimeSpan.FromTicks(10);
    

    Upvotes: 3

    Ilya Ivanov
    Ilya Ivanov

    Reputation: 23626

    There is a couple of static methods, that create TimeSpan from a single parameter:

    TimeSpan.FromSeconds(double seconds)
    TimeSpan.FromMinutes(double minutes)
    

    You can read about all of the on msdn TimeSpan page

    Notice the double parameter, so you can pass 1.5 minutes.

    Upvotes: 2

    Related Questions