I\'m using a method to validate textboxes.
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Toda
Try using TryParseExact
Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. The method returns a value that indicates whether the conversion succeeded.
DateTime.TryParseExact(DateValue,
"dd/mm/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out outDatetime);
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Now;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text,"dd/mm/yyyy",new CultureInfo("en-US"),
DateTimeStyles.None out value))
{
return false;
}
}
return true;
}
DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt))
Use TryParseExact
instead which is also faster.
Example:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string dateString = "27/05/2012"; // <-- Valid
string dtformat = "dd/mm/yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, dtformat, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
}
}
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.