将c#时间跨度四舍五入到5分钟 [英] Round UP c# TimeSpan to 5 minutes

查看:85
本文介绍了将c#时间跨度四舍五入到5分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何处理舍入TimeSpan?

有没有一种方法可以轻松地将c#TimeSpan(可能包含一天以上)向上舍入

Is there a way to easily round a c# TimeSpan (possible containing more than one day) up so that

0天23h 59m变成1天0 h 0 m?

0 days 23h 59m becomes 1 days 0 h 0 m?

0天23h 47m变为0天23h 50 m?

0 days 23h 47m becomes 0 days 23 h 50 m?

等吗?

这是到目前为止我要提出的内容:

Here's what i've come up with so far:

int remainder = span2.Minutes % 5;
if (remainder != 0)
{
    span2 = span2.Add(TimeSpan.FromMinutes(5 - remainder));
}

看起来很简单,但似乎有很多代码:((是否没有某种我可以用来舍入时间跨度的内置c#函数?

it seems like a lot of code for something rather simple:( Isn't there some kind of built in c# function I can use to round timespans?

推荐答案

在这里是

var ts = new TimeSpan(23, 47, 00);
ts = TimeSpan.FromMinutes(5 * Math.Ceiling(ts.TotalMinutes / 5));

或带有一粒糖:

public static class TimeSpanExtensions
{
    public static TimeSpan RoundTo(this TimeSpan timeSpan, int n)
    {
        return TimeSpan.FromMinutes(n * Math.Ceiling(timeSpan.TotalMinutes / n));
    }
}

ts = ts.RoundTo(5);

这篇关于将c#时间跨度四舍五入到5分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆