Maya
Maya

Reputation: 1412

TimeSpan remove seconds

How do you truncate the seconds bit from a timespan object in C#? i.e. 15:37

I'm outputting a timespan object to JavaScript in the format of HH:mm and kind of want the server side to process providing the correct format instead of clients browsers, can that be done without providing this as a C# string object to JavaScript?

Upvotes: 3

Views: 13834

Answers (5)

xmedeko
xmedeko

Reputation: 7805

Maybe not optimal, but easy to read:

TimeSpan.FromMinutes((long)duration.TotalMinutes);

Upvotes: 1

CodesInChaos
CodesInChaos

Reputation: 108790

Perhaps something like this. This truncates to minutes using the truncation of an integer division, followed by a multiplication by the divisor.

return TimeSpan.FromTicks(input.Ticks/TicksPerMinute*TicksPerMinute);

Upvotes: 0

Will Dean
Will Dean

Reputation: 39500

You can truncate the 'ticks' value which is the core of a TimeSpan:

TimeSpan t1 = TimeSpan.FromHours(1.551);
Console.WriteLine(t1);
TimeSpan t2 = new TimeSpan(t1.Ticks - (t1.Ticks % 600000000));
Console.WriteLine(t2);

Gives:

01:33:03.6000000
01:33:00

Upvotes: 9

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

You can use a format string for that:

public string GetTimeSpanAsString(TimeSpan input)
{
    return input.ToString(@"hh\:mm");
}

Upvotes: 20

The Muffin Man
The Muffin Man

Reputation: 20004

I believe this is what you're looking for.

string.Format("{0:H:mm}",myTime)

Upvotes: 0

Related Questions