如何应对取整时间跨度? [英] How to deal with Rounding-off TimeSpan?

查看:280
本文介绍了如何应对取整时间跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要两个日期时间字段之间的差异,并将其存储在一个时间跨度的变量,现在我要舍入的时间跨度由以下规则:

I take the difference between two DateTime fields, and store it in a TimeSpan variable, Now I have to round-off the TimeSpan by the following rules:

如果在时间跨度分钟低于30则分钟和秒必须设置为零,
如果在时间跨度分钟等于或大于30小时,然后必须由1递增,并分钟和秒必须设置为零。

if the minutes in TimeSpan is less than 30 then Minutes and Seconds must be set to zero,
if the minutes in TimeSpan is equal to or greater than 30 then hours must be incremented by 1 and Minutes and Seconds must be set to zero.

时间跨度也可以是负的值,所以在这种情况下,我需要preserve符号..

TimeSpan can also be a negative value, so in that case I need to preserve the sign..

我可以是能够实现的要求,如果时间跨度是不是负值,虽然我已经写了code我很不满意它的低效率,因为它是比较庞大的。

I could be able to achieve the requirement if the TimeSpan wasn't a negative value, though I have written a code I am not happy with its inefficiency as it is more bulky ..

请建议我一个简单,有效的方法。

Please suggest me a simpler and efficient method.

感谢问候,

这是我的code,工作正常,当时间跨度是不是负值。

This is my code which works fine, when TimeSpan is not negative value ..

TimeSpan time_span = endTime.Subtract(startTime);
            TimeSpan time_span1;
            if (time_span.Minutes >= 30)
            {
                time_span1 = new TimeSpan(time_span.Hours + 1, 0, 0);
            }
            else
            {
                time_span1 = new TimeSpan(time_span.Hours, 0, 0);
            }

time_span1将包含..结果

time_span1 will contain the result ..

推荐答案

怎么样:

public static TimeSpan Round(TimeSpan input)
{
    if (input < TimeSpan.Zero)
    {
        return -Round(-input);
    }
    int hours = (int) input.TotalHours;
    if (input.Minutes >= 30)
    {
        hours++;
    }
    return TimeSpan.FromHours(hours);
}

这篇关于如何应对取整时间跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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