Alex
Alex

Reputation: 9720

Input string was not in a correct format when parsed with TimeSpan.ParseExact

I have a DataTable dtTest.

I want to parse one cell from this table from row 2 and colum 2 This cell can have a format of hh:mm:ss or h:mm:ss

I want to parse it to switch to format h.mm or hh.mm

here I verify if there is symbol ":" or not on position 2

string typeTime = dtTest.Rows[2][2].ToString().Substring(1, 1);

Now I parse them:

TimeSpan.ParseExact(dtTest.Rows[2][2].ToString(), 
    typeTime == "." ? "h'.'mm" : "hh'.'mm", CultureInfo.InvariantCulture);

After parsing it gives me an error "Input string was not in a correct format".

Upvotes: 2

Views: 3162

Answers (3)

Oded
Oded

Reputation: 498904

You are trying to parse a string exactly - your string contains a seconds component that does not exist in your format strings. Your string also contains : where you specify ..

The following should work:

TimeSpan.ParseExact(dtTest.Rows[2][2].ToString(), 
    "h':'mm':'ss", CultureInfo.InvariantCulture);

Note that the h format specifier will correctly understand 8 or 08.

Additionally, you can simply use one of the standard TimeSpan format strings - specifically g OR c instead of the custom format string:

TimeSpan.ParseExact(dtTest.Rows[2][2].ToString(), 
    "g", CultureInfo.InvariantCulture);

TimeSpan.ParseExact(dtTest.Rows[2][2].ToString(), 
    "c", CultureInfo.InvariantCulture);

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460038

// zero based row and column index
var rows = dtTest.AsEnumerable();
var secondRow = rows.ElementAtOrDefault(1);
if (secondRow != null)
{
    String secondFieldText = secondRow.Field<String>(1);
    String format = secondFieldText.Length == 8 ? "hh:mm:ss" : "h:mm:ss";
    TimeSpan time = TimeSpan.ParseExact(secondFieldText, format, CultureInfo.InvariantCulture);
}

Upvotes: 1

Danilo Vulović
Danilo Vulović

Reputation: 3063

Try this:

TimeSpan s = TimeSpan.ParseExact(dtTest.Rows[2][2].ToString(), "g", CultureInfo.CurrentCulture);

Upvotes: 1

Related Questions