[英]Is there a more elegant way of removing seconds from a TimeSpan?
假设我有一个等于 07:10:30 的TimeSpan
,我可以使用以下代码从中去除秒数:
myTimeSpan = new TimeSpan(myTimeSpan.Hours, myTimeSpan.Minutes, 0)
这是合适的,还是有更优雅的方法来实现这一目标?
我会建议
TimeSpan.FromMinutes((long) myTimeSpan.TotalMinutes)
这将删除任何小于一分钟的时间组件,同时保留任何更大的组件,如天、小时等。如果您想四舍五入到最接近的分钟而不是截断,请使用Math.Round 。
制作一个向零TimeSpan.TicksPerMinute
入到最近的TimeSpan.TicksPerMinute
的扩展方法。
public static class TimeSpanExtensions
{
public static TimeSpan WithoutSeconds(this TimeSpan ts)
{
const long ps = TimeSpan.TicksPerMinute;
long roundedTicks = ts.Ticks / ps * ps;
return new TimeSpan(roundedTicks);
}
}
参考: https : //docs.microsoft.com/en-us/dotnet/api/system.timespan.ticks? view = net-5.0# System_TimeSpan_Ticks
使用公共时间跨度(长滴答声):
myTimeSpan -= new TimeSpan(myTimeSpan.Seconds * 100000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.