Parse a UK Date String

By default, the DateTime.Parse() method assumes that dates given to it are in US format. In order to get it to process a non-US format date, such as the UK dd/mm/yyyy format, we need to pass it the appropriate "culture" information, like so:

C#

// we need to have imported System.Globalization
// using System.Globalization;

// fetch the en-GB culture
CultureInfo ukCulture = new CultureInfo("en-GB");
// pass the DateTimeFormat information to DateTime.Parse
DateTime myDateTime = DateTime.Parse("18/09/2004",ukCulture.DateTimeFormat);

VB.NET

' we need to have imported System.Globalization
' Imports System.Globalization

' fetch the en-GB culture
Dim ukCulture As CultureInfo = New CultureInfo("en-GB")
' pass the DateTimeFormat information to DateTime.Parse
Dim myDateTime As DateTime = DateTime.Parse("18/09/2004", ukCulture.DateTimeFormat)
 

Once converted, you can then call things like myDateTime.ToShortDateString() and actually get the format you expect - nice! :)

In case you're wondering what that en-GB bit is actually about - the first two characters give the ISO Language Code (ISO 639), and the second two give the ISO Country Code (ISO 3166).

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth