Can you round a .NET TimeSpan object?

0 votes
asked Dec 3, 2008 by buddyjoe

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 TimeSpan object but round it to something like

10 Answers

0 votes
answered Jan 3, 2008 by joel-coehoorn

Not sure about TimeSpan, but you might check this post on DateTimes:

0 votes
answered Jan 3, 2008 by mapache
new TimeSpan(tmspan.Hours, tmspan.Minutes, tmspan.Seconds, (int)Math.Round(Convert.ToDouble(tmspan.Milliseconds / 10)));
0 votes
answered Jan 3, 2008 by will-dean

TimeSpan is little more than a wrapper around the 'Ticks' member. It's pretty easy to create a new TimeSpan from a rounded version of another TimeSpan's Ticks.

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


0 votes
answered Jan 5, 2010 by michael-sorens

Sorry, guys, but both the question and the popular answer so far are wrong :-)

The question is wrong because Tyndall asks for a way to round but shows an example of truncation.

Will Dean's answer is wrong because it also addresses truncation rather than rounding. (I suppose one could argue the answer is right for one of the two questions, but let's leave philosophy aside for the moment...)

Here is a simple technique for rounding:

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

With the input value and number of digits in the sample code, this is the output:

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

Change the precision from 2 digits to 5 digits and get this instead:

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

And even change it to 0 to get this result:

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

Finally, if you want just a bit more control over the output, add some formatting. Here is one example, showing that you can separate the precision from the number of displayed digits. The precision is again set to 2 but 3 digits are displayed, as specified in the last argument of the formatting control string:

Console.WriteLine("Rounded/formatted: " + 
      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 UPDATE: An Out-of-the-box Solution

The above material is useful if you are looking for ideas; I have since had time to implement a packaged solution for those looking for ready-to-use code.

Note that this is uncommented code. The fully commented version with XML-doc-comments will be available in my open source library by the end of the quarter. Though I hesitated to post it "raw" like this, I figure that it could still be of some benefit to interested readers.

This code improves upon my code above which, though it rounded, still showed 7 places, padded with zeroes. This finished version rounds and trims to the specified number of digits.

Here is a sample invocation:

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

And here is the complete RoundedTimeSpan.cs file:

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 UPDATE: Packaged solution now available

I just released a new version of my open-source libraries yesterday, sooner than anticipated, including the RoundedTimeSpan I described above. Code is here; for the API start here then navigate to RoundedTimeSpan under the CleanCode.Data namespace. The CleanCode.DLL library includes the code shown above but provides it in a finished package. Note that I have made a slight improvement in the ToString(int) method above since I posted it on 2010.01.06.

0 votes
answered Jan 26, 2014 by buzz

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)));
0 votes
answered Jan 9, 2016 by cc1960

My solution:

    static TimeSpan RoundToSec(TimeSpan ts)
        return TimeSpan.FromSeconds((int)(ts.TotalSeconds));
0 votes
answered Jan 16, 2016 by netmage

Given some of the comments about rounding to seconds, I thought rounding to any TimeSpan would be nice:

    public static TimeSpan Round(this TimeSpan ts, TimeSpan rnd) {
        if (rnd == TimeSpan.Zero)
            return ts;

        var rndticks = rnd.Ticks;
        var ansTicks = ts.Ticks + rndticks / 2;
        ansTicks -= ansTicks % rndticks;
        return TimeSpan.FromTicks(ansTicks);

    public static TimeSpan Round(this TimeSpan ts) {
        return ts.Round(TimeSpan.FromSeconds(1));
0 votes
answered Jan 19, 2016 by gewalius

Here is a nice Extention-Method:

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

And here are some Examples:

DateTime dt1 = DateTime.Now.RoundToSeconds();  // round to full seconds
DateTime dt2 = DateTime.Now.RoundToSeconds(5 * 60);  // round to full 5 minutes
0 votes
answered Jan 28, 2016 by toolmakersteve

If you want a TimeSpan, its a simple one-liner:

public static TimeSpan RoundSeconds( TimeSpan span, int nDigits ) {
    return TimeSpan.FromSeconds( Math.Round( span.TotalSeconds, nDigits ) );

If you want a string:

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's answer shows use of FromSeconds, but he rounded to whole seconds. My answer generalizes to specified number of digits.

Ed's answer suggests using a format string, and includes a link to the formatting document.

0 votes
answered Sep 15, 2017 by tejaswini

Instead of mathematically trying to round the value, you could simply display only the components of the TimeSpan that you want to show.

TimeSpan currentTimeLapsed = DateTime.Now.Subtract(startTime);
Console.WriteLine (currentTimeLapsed.Hours.ToString() + ":" + currentTimeLapsed.Minutes.ToString() + ":" + currentTimeLapsed.Seconds.ToString());            
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter