Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing time without date in a TextBox

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.

like image 275
Ryan Lundy Avatar asked Dec 30 '22 08:12

Ryan Lundy


2 Answers

You can always cheat the system (quite easily):

DateTime blah = DateTime.Parse("1/1/0001 " + myTimeString);

I've done something similar myself.

like image 150
Timothy Khouri Avatar answered Jan 12 '23 05:01

Timothy Khouri


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.

like image 31
FlySwat Avatar answered Jan 12 '23 06:01

FlySwat