remove seconds from timespan using c#
Asked Answered
I

4

19

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.

Impel answered 19/1, 2012 at 5:0 Comment(6)
You mean for printing? Or do you actually want to 'round' the timespan?Archdiocese
yes i want to convert timespan 00:10:00 value to 00:10 onlyImpel
Thank u so much i got the result.Impel
i have an another doubt how can i check whether the date diff is positive or negative..Impel
@user1065029 If you found some other way remember to add it as answerBuckingham
Accept the right answer and open a new question for "how can i check whether the date diff is positive or negative".Compensate
B
28

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
Buckingham answered 19/1, 2012 at 5:6 Comment(5)
That could be simplified to string.Format("{0:HH\\:mm}", ts); which would display "02:05".Lummox
you should use TotalHours instead of Hours so that you don't get a nasty bug when ts is above 1 day.Rambutan
@BerinLoritsch, I guess you mean hh because HH is not valid format specifier, according to learn.microsoft.com/en-us/dotnet/standard/base-types/…. But then the shortcut can't be used when ts is more than 1 day, see my other comment.Rambutan
@user829755, my bad. HH is valid for date/time objects, but not timespans. In date/time objects, capital specifies 24h clocks but timespans only support 24 hour format.Lummox
Better use TotalHours instead of Hours, to prevent the loss of data when there are more then 24 hoursTedder
A
16

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.

Axon answered 19/1, 2012 at 7:34 Comment(2)
This answer is inacurrate actually, i just tested with some TimeSpan retrieved from TimeZoneInfo. I does work if the value to format is positive, but it will not work for negatives values. Consider: TimeZoneInfo myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); Console.WriteLine($"({myTimeZone.BaseUtcOffset.ToString()})"); Console.WriteLine(myTimeZone.BaseUtcOffset.ToString("hh\\:mm")); Console.WriteLine(string.Format("{0:00}:{1:00}", myTimeZone.BaseUtcOffset.Hours,myTimeZone.BaseUtcOffset.Minutes)); Will produce: (-08:00:00), 08:00 and -08:00.Yesteryear
@GuillaumeZAHRA: You are absolutely right, thanks for the feedback. I have added this caveat (and one other) to my answer.Axon
C
14
TimeSpan newTimeSpan = new TimeSpan(timeSpan.Hours, timeSpan.Minutes, 0);
Contractive answered 15/12, 2014 at 16:33 Comment(0)
S
0

Since there can be more than hours and minutes in a timespan string representation, the most reliable code for removing just the seconds and nothing else would be something like this:

var text = TimeSpan.FromDays(100).ToString(); // "100.00:00:00"
var index = text.LastIndexOf(':');
text = text.Substring(0, index); // "100.00:00"
Superfuse answered 16/3, 2020 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.