I'd recommend you use DateTime.ParseExact
static method, especially this oveload:
DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture
)
This will parse the text you have by the concrete format you specify ("dd/MM/yyyy"
currently, case is important since mm
is minutes as opposed to MM
being months). Use of CultureInfo.InvariantCulture
guarantees that date separators will be retrieved from the format string (the second parameter). I have noticed that if current culture is used, it overrides some aspects of the format string you pass to ParseExact
.
A note on CultureInfo
Invariant culture is good also for the reason that your local dev environment may have different regional information setup than the deployment environment. Usually, .NET uses the current culture in all .ToString
calls and implicit formatting or parsing. When forcing a format and culture invariance explicitly, you are less prone to problems you cannot reproduce locally but exist on the production application.
A note on date/time formats
With exact parsing, the datetime format is expected to strictly match the format of the input. You should then take into consideration the following examples:
dd
matches two-digit days only. So"dd/MM/yyyy"
it will match"01/01/2013"
, but will fail for"1/1/2013"
because it expects the exact number of digits for the day part. If you do not want leading zeros use:d/M/yyyy
instead. Single letter means one digit for days less than10
and two digits for the others.MM
matches two-digit month, so all that applies todd
vs.d
is the same for months.yyyy
expects the year to be in 4 digits. If you use two-digit year, useyy
instead.
A note on some ADO.NET providers
As it turns out to be the case with MS Access, the correctly parsed date-time object is not sufficient to make the query work. Currently, the following code
cmd.Parameters.AddWithValue(...)
is used to add parameters to the query. However, this approach omits passing information to the ADO.NET db provider that tells what database type to use for the parameter. I have read on some forums that MS Access/OleDb is not capable to resolve the correct type in all cases. Therefore I recommend the following approach:
Dim prm as OleDbParameter = _
New OleDbParameter("@dateTimeParameterName", OleDbType.DateTime)
prm.Value = value 'value is an instance of `System.DateTime` parsed
'from the input
cmd.Parameters.Add(prm)
The above code allows to specify the parameter database type explicitly, so the OleDb driver is now capable of correctly passing the DateTime
object to the MS Access database.