你能绕过.NET TimeSpan对象吗?

时间:2008-12-03 21:00:11

标签: .net datetime timespan

你可以围绕一个.NET TimeSpan对象吗?

我的Timespan值为:00:00:00.6193789

是否有一种简单的方法可以将它保留为TimeSpan个对象,但将其四舍五入到类似的东西 00:00:00.62

10 个答案:

答案 0 :(得分:29)

很抱歉,伙计们,但 两者 这个问题和到目前为止流行的答案是错误的: - )

问题是错误的,因为Tyndall要求使用 round 的方法,但会显示 截断 的示例。

Dean的回答是错误的,因为它还解决 截断 而不是 舍入 。 (我想有人可能会认为这两个问题中的一个问题的答案是正确的,但让我们暂时搁置哲学......)

以下是 舍入 的简单技巧:

int precision = 2; // Specify how many digits past the decimal point
TimeSpan t1 = new TimeSpan(19365678); // sample input value

const int TIMESPAN_SIZE = 7; // it always has seven digits
// convert the digitsToShow into a rounding/truncating mask
int factor = (int)Math.Pow(10,(TIMESPAN_SIZE - precision));

Console.WriteLine("Input: " + t1);
TimeSpan truncatedTimeSpan = new TimeSpan(t1.Ticks - (t1.Ticks % factor));
Console.WriteLine("Truncated: " + truncatedTimeSpan);
TimeSpan roundedTimeSpan =
    new TimeSpan(((long)Math.Round((1.0*t1.Ticks/factor))*factor));
Console.WriteLine("Rounded: " + roundedTimeSpan);

使用示例代码中的输入值和位数,这是输出:

Input: 00:00:01.9365678
Truncated: 00:00:01.9300000
Rounded: 00:00:01.9400000

将精度从2位更改为5位数,然后改为:

Input: 00:00:01.9365678
Truncated: 00:00:01.9365600
Rounded: 00:00:01.9365700

甚至将其更改为0即可得到此结果:

Input: 00:00:01.9365678
Truncated: 00:00:01
Rounded: 00:00:02

最后,如果您想要更多地控制输出,请添加一些格式。下面是一个示例,显示您可以将精度与显示的数字分开。精度再次设置为2,但显示3位数,如格式控制字符串的最后一个参数中所指定:

Console.WriteLine("Rounded/formatted: " + 
  string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
      roundedTimeSpan.Hours, roundedTimeSpan.Minutes,
      roundedTimeSpan.Seconds, roundedTimeSpan.Milliseconds));
// Input: 00:00:01.9365678
// Truncated: 00:00:01.9300000
// Rounded: 00:00:01.9400000
// Rounded/formatted: 00:00:01.940

2010.01.06更新:开箱即用的解决方案

如果您正在寻找想法,上述材料非常有用;我已经有时间为那些寻找即用型代码的人实现一个打包的解决方案。

请注意,这是未注释的代码。在本季度末,我的open source library将提供带有XML-doc-comments的完整注释版本。虽然我犹豫是否像这样发布它“原始”,但我认为这对感兴趣的读者来说仍然有一些好处。

这段代码改进了我上面的代码,尽管它已经四舍五入,仍然显示了7个地方,用零填充。此完成版本将舍入并修剪为指定的位数。

以下是一个示例调用:

Console.Write(new RoundedTimeSpan(19365678, 2).ToString());
// Result = 00:00:01.94

这是完整的RoundedTimeSpan.cs文件:

using System;

namespace CleanCode.Data
{
    public struct RoundedTimeSpan
    {

        private const int TIMESPAN_SIZE = 7; // it always has seven digits

        private TimeSpan roundedTimeSpan;
        private int precision;

        public RoundedTimeSpan(long ticks, int precision)
        {
            if (precision < 0) { throw new ArgumentException("precision must be non-negative"); }
            this.precision = precision;
            int factor = (int)System.Math.Pow(10, (TIMESPAN_SIZE - precision));

            // This is only valid for rounding milliseconds-will *not* work on secs/mins/hrs!
            roundedTimeSpan = new TimeSpan(((long)System.Math.Round((1.0 * ticks / factor)) * factor));
        }

        public TimeSpan TimeSpan { get { return roundedTimeSpan; } }

        public override string ToString()
        {
            return ToString(precision);
        }

        public string ToString(int length)
        { // this method revised 2010.01.31
            int digitsToStrip = TIMESPAN_SIZE - length;
            string s = roundedTimeSpan.ToString();
            if (!s.Contains(".") && length == 0) { return s; }
            if (!s.Contains(".")) { s += "." + new string('0', TIMESPAN_SIZE); }
            int subLength = s.Length - digitsToStrip;
            return subLength < 0 ? "" : subLength > s.Length ? s : s.Substring(0, subLength);
        }
    }
}

2010.02.01更新:现已提供打包解决方案

我昨天刚刚发布了一个新版本的开源库,比预期的要早,包括我上面描述的RoundedTimeSpan。代码是here;对于API启动here,然后导航到RoundedTimeSpan命名空间下的CleanCode.Data。 CleanCode.DLL库包含上面显示的代码,但是在完成的包中提供它。请注意,自从我在2010.01.06发布以来,我在ToString(int)方法上略有改进。

答案 1 :(得分:17)

TimeSpan只不过是“Ticks”成员的包装。从另一个TimeSpan的Ticks的圆形版本创建一个新的TimeSpan非常容易。

TimeSpan t1 = new TimeSpan(2345678);
Console.WriteLine(t1);
TimeSpan t2 = new TimeSpan(t1.Ticks - (t1.Ticks % 100000));
Console.WriteLine(t2);

给出:

00:00:00.2345678
00:00:00.2300000

答案 2 :(得分:9)

如果你想要一个TimeSpan,它是一个单行:

public static TimeSpan RoundSeconds( TimeSpan span, int nDigits ) {
    return TimeSpan.FromTicks( (long)( Math.Round( span.TotalSeconds, nDigits ) * TimeSpan.TicksPerSecond) );
    // A simpler one-liner, if not doing more than 3 digits (TimeSpan.FromSeconds rounds to nearest millisecond):
    //return TimeSpan.FromSeconds( Math.Round( span.TotalSeconds, nDigits ) );
}

如果你想要一个字符串:

public static string RoundSecondsAsString( TimeSpan span, int nDigits ) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < nDigits; i++)
        sb.Append( "f" );
    return span.ToString( @"hh\:mm\:ss\." + sb );
}

现金:

cc1960的回答显示了使用FromSeconds,但他整理了几秒。我的答案概括为指定的位数。

Ed的回答建议使用格式字符串,并包含格式文档的链接。

要舍入到其他单位的倍数,例如1/30秒:

    // Rounds span to multiple of "unitInSeconds".
    // NOTE: This will be close to the requested multiple,
    // but is not exact when unit cannot be exactly represented by a double.
    // e.g. "unitInSeconds = 1/30" isn't EXACTLY 1/30,
    // so the returned value won't be exactly a multiple of 1/30.
    public static double RoundMultipleAsSeconds( TimeSpan span, double unitInSeconds )
    {
        return unitInSeconds * Math.Round( span.TotalSeconds / unitInSeconds );
    }

    public static TimeSpan RoundMultipleAsTimeSpan( TimeSpan span, double unitInSeconds )
    {
        return TimeSpan.FromTicks( (long)(RoundMultipleAsSeconds( span, unitInSeconds ) * TimeSpan.TicksPerSecond) );

        // IF USE THIS: TimeSpan.FromSeconds rounds the result to nearest millisecond.
        //return TimeSpan.FromSeconds( RoundMultipleAsSeconds( span, unitInSeconds ) );
    }

    // Rounds "span / n".
    // NOTE: This version might be a hair closer in some cases,
    // but probably not enough to matter, and can only represent units that are "1 / N" seconds.
    public static double RoundOneOverNAsSeconds( TimeSpan span, double n )
    {
        return Math.Round( span.TotalSeconds * n ) / n;
    }

    public static TimeSpan RoundOneOverNAsTimeSpan( TimeSpan span, double n )
    {
        return TimeSpan.FromTicks( (long)(RoundOneOverNAsSeconds( span, n ) * TimeSpan.TicksPerSecond) );

        // IF USE THIS: TimeSpan.FromSeconds rounds the result to nearest millisecond.
        //return TimeSpan.FromSeconds( RoundOneOverNAsSeconds( span, n ) );
    }

使用其中一个来舍入到1/30秒的倍数:

    private void Test()
    {
        long ticks = (long) (987.654321 * TimeSpan.TicksPerSecond);
        TimeSpan span = TimeSpan.FromTicks( ticks );
        TestRound( span, 30 );
        TestRound( TimeSpan.FromSeconds( 987 ), 30 );
    }

    private static void TestRound(TimeSpan span, int n)
    {
        var answer1 = RoundMultipleAsSeconds( span, 1.0 / n );
        var answer2 = RoundMultipleAsTimeSpan( span, 1.0 / n );
        var answer3 = RoundOneOverNAsSeconds( span, n );
        var answer4 = RoundOneOverNAsTimeSpan( span, n );
    }

在调试器中查看结果:

// for 987.654321 seconds:
    answer1 987.66666666666663  double
    answer2 {00:16:27.6666666}  System.TimeSpan
    answer3 987.66666666666663  double
    answer4 {00:16:27.6666666}  System.TimeSpan

// for 987 seconds:
    answer1 987 double
    answer2 {00:16:27}  System.TimeSpan
    answer3 987 double
    answer4 {00:16:27}  System.TimeSpan

答案 3 :(得分:4)

考虑到有关舍入到秒的一些评论,我认为四舍五入到任何TimeSpan都会很好:

public static TimeSpan Round(this TimeSpan ts, TimeSpan rnd) {
    if (rnd == TimeSpan.Zero)
        return ts;
    else {
        var rndticks = rnd.Ticks;
        var ansTicks = ts.Ticks + rndticks / 2;
        return TimeSpan.FromTicks(ansTicks - ansTicks % rndticks);
    }
}
public static TimeSpan Round(this TimeSpan ts) => ts.Round(TimeSpan.FromSeconds(1));

考虑到处理小数单位时可能出现的不精确问题(根据@ToolmakerSteve),我会在你需要更高精度时添加一个小数舍入选项,并四舍五入到计算机小数秒:

public static TimeSpan RoundToFraction(this TimeSpan ts, long num, long den) => (den == 0.0) ? TimeSpan.Zero : TimeSpan.FromTicks((long)Math.Round(Math.Round((double)ts.Ticks * (double)den / num / TimeSpan.TicksPerSecond) * (double)num / den * TimeSpan.TicksPerSecond));
public static TimeSpan RoundToFraction(this TimeSpan ts, long den) => (den == 0.0) ? TimeSpan.Zero : TimeSpan.FromTicks((long)(Math.Round((double)ts.Ticks * den / TimeSpan.TicksPerSecond) / den * TimeSpan.TicksPerSecond));

答案 4 :(得分:3)

new TimeSpan(tmspan.Hours, tmspan.Minutes, tmspan.Seconds, (int)Math.Round(Convert.ToDouble(tmspan.Milliseconds / 10)));

答案 5 :(得分:1)

不确定TimeSpan,但您可以在DateTimes上查看此帖子:
http://mikeinmadison.wordpress.com/2008/03/12/datetimeround/

答案 6 :(得分:1)

这是一个很好的扩展方法:

    public static TimeSpan RoundToSeconds(this TimeSpan timespan, int seconds = 1)
    {
        long offset = (timespan.Ticks >= 0) ? TimeSpan.TicksPerSecond / 2 : TimeSpan.TicksPerSecond / -2;
        return TimeSpan.FromTicks((timespan.Ticks + offset) / TimeSpan.TicksPerSecond * TimeSpan.TicksPerSecond);
    }

以下是一些例子:

DateTime dt1 = DateTime.Now.RoundToSeconds();  // round to full seconds
DateTime dt2 = DateTime.Now.RoundToSeconds(5 * 60);  // round to full 5 minutes

答案 7 :(得分:1)

我的解决方案:

    static TimeSpan RoundToSec(TimeSpan ts)
    {
        return TimeSpan.FromSeconds((int)(ts.TotalSeconds));
    }

答案 8 :(得分:0)

另一种将毫秒数舍入到最接近的秒数的方法。

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)));

答案 9 :(得分:0)

一种扩展方法,如果您需要使用npm install,但仍然想舍入时间。就我而言,我想四舍五入。

DateTime