Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice in checking if a string is a datetime before converting?

Tags:

c#

What's the best way to do it?

This is how I'll usually do it:

DateTime newDate;

try
{
    newDate = DateTime.Parse(Textbox.Text);
}
catch
{
    //isn't a datetime
    return;
}

//do stuff with the date

But something tells me that that is a bit wrong. Any ideas?

like image 962
John Avatar asked Oct 16 '09 04:10

John


People also ask

What happens if the DateTime parse () method Cannot convert to a DateTime type?

C# DateTime FormatException If the DateTime. Parse method fails, it throws a FormatException . In the example, we handle a FormatException . $ dotnet run failed to parse string System.

How do I convert a string to a DateTime?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

What is parsing how do you parse a date time string?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What does DateTime ParseExact do?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


3 Answers

Use the DateTime.TryParse method instead of using your own try/catch blocks.

string text = "10/16/2009";
DateTime result;

if (DateTime.TryParse(text, out result))
{
    // success, result holds converted value
}
else
{
    // failed
}
like image 61
Ahmad Mageed Avatar answered Nov 02 '22 03:11

Ahmad Mageed


The best pattern to use for datetime parsing would be this

string DateFormat = "dd/MM/yyyy"; //Or any other format
DateTime dateTime;
bool success = DateTime.TryParseExact(value, DateFormat, 
       CultureInfo.InvariantCulture, 
           DateTimeStyles.None, 
                out dateTime);

Never use DateTime.Parse and even DateTime.TryParse

like image 38
Binoj Antony Avatar answered Nov 02 '22 04:11

Binoj Antony


If you know what the format of the datetime will be, you can also use DateTime..::.TryParseExact Method

The DateTime.TryParse can cause problems when it is used with dates such as 01/03/2009

Is it 01 Mar or 03 Jan?

I would rather recomend that you use something other than a textbox, like a date picker, or validate the textbox so that you have something like dd MMM yyyy. very seldomly would you go wrong with that.

like image 27
Adriaan Stander Avatar answered Nov 02 '22 03:11

Adriaan Stander