views:

1057

answers:

4

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.

+3  A: 

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.

FlySwat
A: 

Come to think of it, never mind. I just noticed that if I use "am" and "pm" instead of "a" and "p", it works fine. It assumes today's date, instead of the default 1/1/0001, but that's not a problem for my purposes.

(Still, any reasonably easy solution to get the "a" and "p" to work is welcome.)

Kyralessa
This is what I mean about the idiot user test =)
FlySwat
You could add the letter m to the user's input if it doesn't pass the first TryParse. Not sure it's a good idea though
dub
That's a very good thought, dub. Kind of cheesy :), but a special case like that is all I really need.
Kyralessa
A: 

You may be able to use the validating or validated event to capture the text and add the 'm'.

SeaDrive
A: 

You can always cheat the system (quite easily):

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

I've done something similar myself.

Timothy Khouri