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?
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.
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.
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.
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.
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
}
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
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.
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