remove seconds from timespan using c#

随声附和 提交于 2019-12-09 10:20:54

问题


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.


回答1:


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



回答2:


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");



回答3:


TimeSpan newTimeSpan = new TimeSpan(timeSpan.Hours, timeSpan.Minutes, 0);


来源:https://stackoverflow.com/questions/8921236/remove-seconds-from-timespan-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!