简体   繁体   English

使用 c# 从时间跨度中删除秒

[英]remove seconds from timespan using c#

I want to remove the seconds from timespan using c#我想使用 c# 从时间跨度中删除秒数

My code is here:我的代码在这里:

TimeSpan lateaftertime = new TimeSpan();
lateaftertime =  lateafter - Convert.ToDateTime(intime) ;

It returns the value 00:10:00它返回值00:10:00

But i want the below output : 00:10 only not seconds field :00 .但我想要以下输出: 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 .请注意, TimeSpan没有格式 It's stored in some internal representation which does not resemble 00:10:00 at all.它存储在一些完全不像00:10:00内部表示中。

The usual format hh:mm:ss is only produced when the TimeSpan is converted into a String , either explicitly or implicitly.通常的格式hh:mm:ss仅在 TimeSpan 显式或隐式转换为String时产生。 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 .您问题中的代码示例“为时过早”——此时, TimeSpan 仍然是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 的转换,您可以使用String.Format ,如 V4Vendetta 的答案中所建议的,或者您可以使用TimeSpan.ToString自定义格式字符串(可用于 .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.如果 TimeSpan 跨度超过 24 小时,它只会显示时间间隔中不属于一整天的小时数。

    Example: new TimeSpan(26, 0, 0).ToString("hh\\\\:mm") yields 02:00 .示例: new TimeSpan(26, 0, 0).ToString("hh\\\\:mm")产生02:00 This can be fixed by adding the d custom format specifier .这可以通过添加d 自定义格式说明符来解决

  • 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.自定义 TimeSpan 格式说明符不支持包含符号符号,因此您将无法区分负时间间隔和正时间间隔。

    Example: new TimeSpan(-2, 0, 0).ToString("hh\\\\:mm") yields 02:00 .示例: new TimeSpan(-2, 0, 0).ToString("hh\\\\:mm")产生02:00

TimeSpan newTimeSpan = new TimeSpan(timeSpan.Hours, timeSpan.Minutes, 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM