Erica Stockwell-Alpert
Erica Stockwell-Alpert

Reputation: 4863

How do I parse an international date string into a DateTime object? VB.NET

I have a couple DateTime inputs in a form, which display international format. For example, when a Canadian user selects a date it shows up as 17/03/2016. I'm trying to parse this string into a date (to make sure it's valid date and not something like "cat"), but the parsing function isn't recognizing the international dates as valid dates. unsubscribedFrom and unsubscribedTo are strings that are being passed in from the form, which I then pass into a SQL query

Dim unsubscribedFromDate As DateTime
Dim unsubscribedToDate As DateTime

If DateTime.TryParse(unsubscribedFrom, unsubscribedFromDate) Then
    unsubscribedFrom = unsubscribedFromDate.ToEST().ToShortDateString()
    PageSectionWhereClause &= "AND es.DateUnsubscribed >= CONVERT(DateTime, '" & unsubscribedFrom & "')" & Environment.NewLine
End If
If DateTime.TryParse(unsubscribedTo, unsubscribedToDate) Then
    unsubscribedTo = unsubscribedToDate.ToEST().ToShortDateString()
    PageSectionWhereClause &= "AND es.DateUnsubscribed >= CONVERT(DateTime, '" & unsubscribedTo & "')" & Environment.NewLine
End If

When unsubscribedFrom = "17/03/2016", DateTime.TryParse fails.

NOTE: My code needs to handle international AND non-international dates, it's possible to get both.

Upvotes: 0

Views: 1268

Answers (1)

Dai
Dai

Reputation: 155448

Generally, never use DateTime.Parse or DateTime.TryParse - because they default to using your user account's default date formatting - if you're in the US then that's MM/dd/yyyy (when pretty much the entire rest of the world uses dd/MM/yyyy).

If you know beforehand what format they're using you should use DateTime.ParseExact or DateTime.TryParseExact.

DateTime value = DateTime.ParseExact("dd/MM/yyy", input);

If you know the user is from a particular country but unsure of the format then specify an explicit CultureInfo:

DateTime value = DateTime.Parse( CultureInfo.GetCulture("en-CA"), input);

Upvotes: 1

Related Questions