Jehof
Jehof

Reputation: 35544

Parse string representation of time values to TimeSpan

I have an XML-File that contains multiple Attributes, that contains time values and I need to sum these values up.

<test>
   <value time="0.345"/>
   <value time="0.756"/>
   <value time="0.455"/>
</test>

But the problem is that TimeSpan.Parse("0.345") does not parse the value and results in an Exception. Event using TimeSpan.Parse("0.345",System.Globalization.CultureInfo.GetCultureInfo("en-us")) results in the exception.

Message
Die Zeichenfolge wurde nicht als gültiger TimeSpan erkannt. 

StackTrace
   bei System.Globalization.TimeSpanParse.TimeSpanResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName)
   bei System.Globalization.TimeSpanParse.ProcessTerminal_HM(TimeSpanRawInfo& raw, TimeSpanStandardStyles style, TimeSpanResult& result)
   bei System.Globalization.TimeSpanParse.ProcessTerminalState(TimeSpanRawInfo& raw, TimeSpanStandardStyles style, TimeSpanResult& result)
   bei System.Globalization.TimeSpanParse.TryParseTimeSpan(String input, TimeSpanStandardStyles style, IFormatProvider formatProvider, TimeSpanResult& result)
   bei System.TimeSpan.Parse(String s)

So whats the correct ways to parse these time values to TimeSpan, so i can sum these values up?

Upvotes: 1

Views: 931

Answers (5)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

Well, you can't parse this value with TimeSpan.Parse method.

From documentation;

[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]

Elements in square brackets ([ and ]) are optional. One selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required.

As you can see, you don't have the hour and minutes part required. That's why you get FormatException.

One solution could be concatenation your string values with "0:0:" to get strings like "0:0:0.345" which can be parsed successfully.

TimeSpan.Parse("0:0:0.345", new CultureInfo("de-DE")); // 00:00:00.3450000

Upvotes: 2

NeatNerd
NeatNerd

Reputation: 2373

If you have only seconds, use TimeSpan.FromSeconds

EDIT: for string in op:

 string s = "0.455"
 var span = TimeSpan.FromSeconds(Convert.ToDouble(s))

Upvotes: 1

faby
faby

Reputation: 7558

try in this way with TimeSpan.FromSeconds

   var x=@"<root>
            <value time=""0.345""/>
            <value time=""0.756""/>
            <value time=""0.455""/>
        </root>";

   TextReader tr = new StringReader(x);
   var doc = XDocument.Load(tr);
   var timeSpanResult = TimeSpan.FromSeconds(doc.Descendants("value").Sum(
                y =>
                {
                    double value;
                    if (double.TryParse(y.Attribute("time").Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
                    {
                        return value;
                    }
                    return 0;
                }));

I am assuming that values are all fractional seconds. At the end your timeSpanResult variable will store the correct value

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460018

It depends on what 1 means for you, one hour, minute, second, day, year ....

Presuming it means hour:

decimal hourFraction = decimal.Parse("0.345", CultureInfo.InvariantCulture);
long ticks = (long)(hourFraction * TimeSpan.FromHours(1).Ticks);
TimeSpan duration = new TimeSpan(ticks); // approximately 20 minutes

Once you have all TimeSpan values(f.e. in a List<TimeSpan>) you can use Enumerable.Sum:

TimeSpan sumDuration = new TimeSpan(allDurations.Sum(t => t.Ticks));

Upvotes: 2

lawliet29
lawliet29

Reputation: 355

You can parse the value as double and use TimeSpan.FromSeconds method.

Upvotes: 0

Related Questions