TimeSpan remove seconds
13,273
Solution 1
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
Solution 2
You can use a format string for that:
public string GetTimeSpanAsString(TimeSpan input)
{
return input.ToString(@"hh\:mm");
}
Solution 3
Maybe not optimal, but easy to read:
TimeSpan.FromMinutes((long)duration.TotalMinutes);
Author by
Maya
Updated on June 04, 2022Comments
-
Maya almost 2 years
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?
-
Fredrik Mörk about 13 yearsThat code crashes if
myTime
is aTimeSpan
(System.FormatException: Input string was not in a correct format.) -
Maya about 13 yearsThanks but I need 01:33 output in my case
-
The Muffin Man about 13 years@Fredrik, sorry, however
H:mm
should be the converter your looking for. -
CodesInChaos about 13 years@Maya "1:33" is a string. You just said you wanted a TimeSpan and not a string.
-
Will Dean about 13 yearsThen you need to send a preformatted string, not a TimeSpan. I read the question has 'how do I do this without sending a string', sorry.
-
Maya about 13 years@CodeInChaos @will-dean thanks Will I thought there is a way to produce the hh:mm format AS a TimeSpan without converting to String.
-
Chris Van Opstal about 13 years@Maya I think you're going to have to either modify your JSON serializer or do this on the client side. Or just modify the value you're sending to your serializer and send a string instead.
-
Fredrik Mörk about 13 yearsI don't understand what you mean.
H:mm
is not a valid format string for aTimeSpan
. For aDateTime
yes, but not forTimeSpan
. -
CodesInChaos about 13 yearsA TimeSpan has no format. It's just an integral number of ticks. I think what you want is changing how it's serialized to json, and not the TimeSpan itself.
-
Will Dean about 13 years@Maya - TimeSpan doesn't have any particular string representation until someone converts it into a string - pretty much all .NET types work like this. Though you could create one which carried its format with it, that isn't the way the standard types work.
-
The Muffin Man about 13 years@Fredrik, I was under the impression that it would parse the string for a time and convert it to the specified format. I apologize for giving you false information.
-
Maya about 13 yearsOk fair enough, that clears things up for me, many thanks guys, a +1 vote for you all :)
-
Darren almost 9 yearsGreat answer, but I would use TimeSpan.TicksPerMinute instead of 600000000.