Avatar of Dinesh Bali
Dinesh Bali
 asked on

Converting string to Timespan

Hi,

I am working in c# ASP.net

I need help in creating logic. I might get the time in different format. I don;t want to put so many if and else.

My time format might comes from input fields like this

00:14:54
00:14:54.4
00:14:54.49
00:14:54.494
00:14:54.4942
00:14:54.49427
00:14:54.494271

Now, I wanted to convert the above in the Timespan. My below code gives error because I have 5 digits after "." and I have 6 f (.ffffff) in the timespan format.


TimeSpan timeSpan = TimeSpan.ParseExact("00:14:54.49427", @"hh\:mm\:ss\.ffffff", CultureInfo.InvariantCulture, TimeSpanStyles.None);

Open in new window


Error:
Stack Trace:


[System.FormatException: Input string was not in a correct format.]
   at System.Globalization.TimeSpanParse.TryParseByFormat(String input, String format, TimeSpanStyles styles, TimeSpanResult& result)
   at System.Globalization.TimeSpanParse.TryParseExactTimeSpan(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, TimeSpanResult& result)
   at System.Globalization.TimeSpanParse.ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
   at System.TimeSpan.ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
   at Program.Main() :line 9

Open in new window

   
   Please help me creating good logic to get timespan from any of the formats.

Kind Regards,

ASP.NETC#

Avatar of undefined
Last Comment
Jonathan D.

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
AndyAinscow

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jonathan D.

Use Regex to determine the length of the input and then use ParseExact to parse the input.

Edit: I want to reinforce Andy's comment and say that since C# 7.0 there's been a tiny improvement to the output parameter feature which prevents code smell. Basically his code could be refactored to include the variable type inline the out to prevent redundant declaration.

TimeSpan.TryParse(Input, out TimeSpan result);

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck