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?
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?
Share Improve this question asked Feb 24, 2011 at 22:44 MayaMaya 1,4125 gold badges23 silver badges44 bronze badges 6 | Show 1 more comment5 Answers
Reset to default 20You can use a format string for that:
public string GetTimeSpanAsString(TimeSpan input)
{
return input.ToString(@"hh\:mm");
}
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
Maybe not optimal, but easy to read:
TimeSpan.FromMinutes((long)duration.TotalMinutes);
I believe this is what you're looking for.
string.Format("{0:H:mm}",myTime)
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);
TimeSpan
is a value, not a string representation of a value. If you need it in a specific format, you will need to convert it to a string. – Fredrik Mörk Commented Feb 24, 2011 at 23:04