Can you round a .NET TimeSpan object?

后端 未结 10 949
渐次进展
渐次进展 2020-12-03 03:01

Can you round a .NET TimeSpan object?

I have a Timespan value of: 00:00:00.6193789

Is there a simple way to keep it a TimeSp

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 03:26

    Yet another way to round milliseconds to the nearest second.

    private const long TicksPer1000Milliseconds = 1000 * TimeSpan.TicksPerMillisecond;
    
    // Round milliseconds to nearest second
    // To round up, add the sub-second ticks required to reach the next second
    // To round down, subtract the sub-second ticks
    elapsedTime = new TimeSpan(elapsedTime.Ticks + (elapsedTime.Milliseconds >= 500 ? TicksPer1000Milliseconds - (elapsedTime.Ticks % TicksPer1000Milliseconds) : -(elapsedTime.Ticks % TicksPer1000Milliseconds)));
    

提交回复
热议问题