I want to remove the seconds from timespan using c#
My code is here:
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = lateafter - Convert.ToDateTime(intime) ;
It returns the value 00:10:00
But i want the below output :00:10
only not seconds field :00
.
Well you can simply do as
string.Format("{0}:{1}", ts.Hours,ts.Minutes) // it would display 2:5
EDIT
to get it properly formatted use
string.Format("{0:00}:{1:00}", ts.Hours,ts.Minutes) // it should display 02:05
Note that a TimeSpan
does not have a format. It's stored in some internal representation¹ which does not resemble 00:10:00
at all.
The usual format hh:mm:ss
is only produced when the TimeSpan is converted into a String
, either explicitly or implicitly. Thus, the conversion is the point where you need to do something. The code example in your question is "too early" -- at this point, the TimeSpan is still of type TimeSpan
.
To modify the conversion to String, you can either use String.Format
, as suggested in V4Vendetta's answer, or you can use a custom format string for TimeSpan.ToString (available with .NET 4):
string formattedTimespan = ts.ToString("hh\\:mm");
Note that this format string has the following drawbacks:
If the TimeSpan spans more than 24 hours, it will only display the number of whole hours in the time interval that aren't part of a full day.
Example: new TimeSpan(26, 0, 0).ToString("hh\\:mm")
yields 02:00
. This can be fixed by adding the d
custom format specifier.
Custom TimeSpan format specifiers don't support including a sign symbol, so you won't be able to differentiate between negative and positive time intervals.
Example: new TimeSpan(-2, 0, 0).ToString("hh\\:mm")
yields 02:00
.
¹ TimeSpan
is just a thin wrapper around a 64-bit integer containing the number of ticks (10,000 ticks = 1 millisecond). Thus, 00:10:00
will be stored as the number 6,000,000,000
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With