I'm working on a time sheet application, where I'd like the user to be able to enter times in TextBoxes, e.g.: 8 a or 8:00 a or the like, just like you can in Excel.
Now if you enter a date in a TextBox and then use DateTime.TryParse, you can enter it in several formats (Jan 31, 2007; 1/31/2007; 31/1/2007; January 31, 2007; etc.) and .NET will figure it out and turn it into a DateTime.
But when I use DateTime.TryParse on a string like "8 a" or "8:00 a", it doesn't understand it.
I know I can use ParseExact, but I'm wondering if there's a more flexible solution. I want .NET to get 8:00a from "8 a" or "8:00 a", and to leave the date component at the default 1/1/0001.
You can always cheat the system (quite easily):
DateTime blah = DateTime.Parse("1/1/0001 " + myTimeString);
I've done something similar myself.
I'd reconsider your UI functionality and replace it with two combo boxes, or some other form of time picker.
Ultimately, even the best time parser in the world will still fail the idiot user test.
Barring that, Parse.Exact is what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With