I have this absurd situation where i need to support a Custom TimeSpan Format with a unit of Tenths of minutes with Timespan.TryParse.

i.e. hh:mm:t

where t denotes 10ths of minute (6 second intervals)

What would be the easiest way of adding this to the Custom Timespan format parsing specifies?

Is there some override facility that would make this easy?

Edit

var mask = "hmmt";
var value = "0011";

// 0 hours
// 01 minutes
// 1 tenths of minutes


TimeSpan.TryParseExact(value, mask, null, out time)

the mask is configurable by the user and i need the ability to add some sort of custom specifier like "t" to denote tenths of minutes the user in essence adds this mask, as the value comes from various pabx phone systems that output duration's in many weird and wonderful ways. one of those ways is the use of 10ths of minutes

有帮助吗?

解决方案

if I understand correctly, then for example .3 at the end means 3/10 of a minute, making it 18 seconds. If so, this is the way, in case you have time like "hh:mm:t" as you wrote:

public static class TimeSpanExtension
{
    public static TimeSpan TryParseTenth(string timeSpanString)
    {
        //change following line to accomodate date format if needed
        timeSpanString += "0";
        TimeSpan ts = new TimeSpan();
        if (TimeSpan.TryParse(timeSpanString, out ts))
        {
            // recalculate from tenth of minute into seconds
            float realSeconds = ts.Seconds * 60 / 100;

            //final operation to correct
            return ts.Subtract(new TimeSpan(0, 0, ts.Seconds - (int)realSeconds));
        }
        else
            return TimeSpan.Zero;
    }
}

usage:

   string time = "06:55:3";
   var timeSpan = TimeSpanExtension.TryParseTenth(time);

resulting in 6h55m18s as I wrote at the top

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top