Alaa Khalil
Alaa Khalil

Reputation: 77

Input string was not in a correct format. in timespan

TimeSpan newEventStartTime = TimeSpan.ParseExact(Start_Time, "HH:mm", CultureInfo.InvariantCulture);

when this line of code execute ,it make an error Input string was not in a correct format. and the variable Start_Time data type is string in c# and it's data type in java script is time.

Upvotes: 8

Views: 8058

Answers (2)

Matthew Haugen
Matthew Haugen

Reputation: 13286

I had trouble doing something like this myself not too long ago. There are a couple of things here that need to be modified in your format string.

  1. Since the TimeSpan type refers to hours in the time passage sense and not the hour-of-day sense (even though, yes, it is used to show the time of day as well), you want lowercase hs. Uppercase means 24-hour clock, and that's irrelevant when you don't have the concept of AM and PM, which TimeSpans don't.
  2. You need to escape the colon to make it persist through the parse as a literal.

Given that, you can do this instead:

TimeSpan newEventStartTime = TimeSpan.ParseExact(Start_Time, @"hh\:mm", CultureInfo.InvariantCulture);

You can review the Custom TimeSpan Format Strings MSDN page if you need help past this, but I definitely agree that this isn't the best-documented or easiest to overcome bug in the world.


This is most likely irrelevant to you, but I'm including it just in good practice. That's only if you really want to preserve that exact format string. If you're okay being a little more lenient, you could use the "c" format-designator instead. That allows for more details to be preserved from an incoming string. The choice between those options is really just up to you and the circumstances in which you're hoping to use this. But again, since you even thought to use ParseExact over Parse in the first place, I suspect the example I gave above with @"hh\:mm" is what you're looking for.

Upvotes: 11

gaurav
gaurav

Reputation: 230

Try this. it's working fine. if any other doubts please let me know.

TimeSpan newEventStartTime = TimeSpan.ParseExact("12:44",@"hh\:mm",CultureInfo.InvariantCulture);

see dotnetfiddle link https://dotnetfiddle.net/In71Rh

Upvotes: 6

Related Questions