views:

195

answers:

1

How to (try)parse a single String to DateTime in "DD/MM/YYYY" format? (VB.Net)

For example: I use input string "30/12/1999" (30 December 1999), how to (try)parse it to DateTime?

+2  A: 

Try this:

Dim date As Datetime = DateTime.ParseExact(_
    yourString, "dd/MM/yyyy", CultureInfo.InvariantCulture)

This will throw an exception if yourString does not match the format you specify. If you do not want an exception in this case then do this:

Dim date As Date    
Date.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.CurrentCulture, _
                      DateTimeStyles.None, date)
Andrew Hare
Thanks, it's working!
lesderid
I will handle the exception instead of TryParse.Thank you again. Answer accepted!
lesderid
Note: if you expect that the string won't always be a valid date, TryParse and TryParseExact are generally faster. (Throwing and catching exceptions can be expensive.) Also, they return a boolean indicating whether they could parse the date.
cHao