troubleshooting Question

Converting string to Timespan

Avatar of Dinesh Bali
Dinesh Bali asked on
ASP.NETC#
2 Comments1 Solution13 ViewsLast Modified:
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);

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
   
   Please help me creating good logic to get timespan from any of the formats.

Kind Regards,

ASKER CERTIFIED SOLUTION
AndyAinscow
Freelance programmer / Consultant

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros