简体   繁体   English

有没有更优雅的方式从 TimeSpan 中删除秒数?

[英]Is there a more elegant way of removing seconds from a TimeSpan?

Assuming I have a TimeSpan that is equal to 07:10:30, I can use the following code to strip the seconds from it:假设我有一个等于 07:10:30 的TimeSpan ,我可以使用以下代码从中去除秒数:

myTimeSpan = new TimeSpan(myTimeSpan.Hours, myTimeSpan.Minutes, 0)

Is this appropriate, or is there a more elegant way to achieve this?这是合适的,还是有更优雅的方法来实现这一目标?

I would propose我会建议

TimeSpan.FromMinutes((long) myTimeSpan.TotalMinutes)

This removes any time component smaller than one minute, while keeping anything larger, like days, hours etc. Use Math.Round if you want rounding to nearest minute instead of truncating.这将删除任何小于一分钟的时间组件,同时保留任何更大的组件,如天、小时等。如果您想四舍五入到最接近的分钟而不是截断,请使用Math.Round

Make an extension method that rounds towards zero to the nearest TimeSpan.TicksPerMinute .制作一个向零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);
    }
}

Ref: https://docs.microsoft.com/en-us/dotnet/api/system.timespan.ticks?view=net-5.0#System_TimeSpan_Ticks参考: 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.

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