-4

Lets say for example I want the user to enter a time, the input must be in the format HH:MM and the input must contain the colon on in the users input, how would I go about creating this and storing it?

The input will come from a text box on a WPF window

  • input where? which platform? what _have_ you tried so far, what are the difficulties that _you_ have encountered? – styx Nov 08 '18 at 10:23
  • 1
    Usually (the simplest option) we use `DateTime` type for storing (`Date` or/and `Time`) something like this: `if (DateTime.TryParseExact(userInputHere, "HH':'mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime result)) {/* ..valid time in the result.TimeOfDay ... */} else {/* .. invalid time ...*/}` – Dmitry Bychenko Nov 08 '18 at 10:44
  • It has to be a TextBox? There are some custom time picker controls, which might do what you want. Those are not default WPF controls though. – nilsK Nov 08 '18 at 10:49

1 Answers1

0

not really precise question, but let me help a little bit:

Here is a simple example on how to parse a string like one you could have, and store it in a DateTime variable (which is probably the clean solution if you want to display it with a different format later and so on).

string text = "21:05"; (instead you retrieve the content of your text box obviously)
string format = "HH:mm";
CultureInfo fr = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(text, format, fr);

[EDIT] based on Dmitry comment:

string text = "21:05";
string format = "HH:mm";
CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture;
DateTime dt;
if (DateTime.TryParseExact(text, format, invariant, DateTimeStyles.None, out dt))
{
// do your stuff
}
else
{
// handle the fact you cannot parse the datetime
}

Be careful, the cultural context may be really important depending on your case. If you want to avoid bad input from user, you should think about implementing a validation on the box content when the user is typing in it. It's a way to force him conform to the format you are expecting.

Look here for example: Implement Validation for WPF TextBoxes but you should be able to find other examples on how to do that on SO or just google it.

Mikitori
  • 589
  • 9
  • 21
  • 2
    I'd rather put it as `DateTime.TryParseExact` (please, note `Try`): when working with *user input* we should be ready for *arbitrary string* (e.g. `45:93` or `bla-bla-bla`) – Dmitry Bychenko Nov 08 '18 at 10:45
  • 1
    I put the CultureInfo.InvariantCulture to show some of the possibilities, I'll let Callum check what he really needs – Mikitori Nov 08 '18 at 11:00