Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid date check with DateTime.TryParse method

I am using Datetime.TryParse method to check the valid datetime. the input date string would be any string data. but is returning false as the specify date in invalid.

DateTime fromDateValue;
if (DateTime.TryParse("15/07/2012", out fromDateValue))
{
    //do for valid date
}
else
{
    //do for in-valid date
}

Edit: I missed. I need to check the valid date with time as "15/07/2012 12:00:00".

Any suggestions are welcome.

like image 696
Sujit Avatar asked Jul 03 '12 12:07

Sujit


People also ask

How does DateTime TryParse work?

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

What is TryParse used for?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.

How check DateTime is valid or not in C#?

Use the DateTime. TryParseExact method in C# for Date Format validation. They method converts the specified string representation of a date and time to its DateTime equivalent. It checks whether the entered date format is correct or not.


2 Answers

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

So for example:

DateTime fromDateValue;
string s = "15/07/2012";
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
    // do for valid date
}
else
{
    // do for invalid date
}
like image 155
Darin Dimitrov Avatar answered Oct 20 '22 00:10

Darin Dimitrov


You should be using TryParseExact as you seem to have the format fixed in your case.

Something like can also work for you

DateTime.ParseExact([yourdatehere],
                    new[] { "dd/MM/yyyy", "dd/M/yyyy" },
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None);
like image 41
V4Vendetta Avatar answered Oct 19 '22 23:10

V4Vendetta