简体   繁体   中英

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.

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 h s. Uppercase means 24-hour clock, and that's irrelevant when you don't have the concept of AM and PM, which TimeSpan s 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM