I'm using a method to validate textboxes.
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Today;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text, out value))
{
return false;
}
}
return true;
}
I want to check the format too. It requires mm/dd/yyyy
, but want it to be dd/mm/yyyy
TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.
For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
Try DateTime.TryParseExact
DateTime dt;
DateTime.TryParseExact(textBox.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
If you want to check multiple formats as you updated in your question then you can do using another overload method of TryParseExact
which takes format
parameter as array of string.
string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy" };
DateTime.TryParseExact(txtBox.Text,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out value));
Please take care of format string. As you have mentioned format as dd/mm/yyyy
. Here mm
represents the minute
not the month. Use MM
for the month representation.
DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt))
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