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).
This thread is for discussions of Parse a UK Date String.
DateTime.ParseExact("date time string", format, CultureInfo.currentCulture)
the Date time string is the string that you want.
format is the way you want the String to be read dd = day, MM = month, yyyy = four digit year, yy is 2 digit year, HH = 24 Hours clock, hh = 12 hour clock,
mm = minutes, ss = seconds.
cultureinfo.currentculture takes on the deault culture you can change it to anything you want.
the advantage is that it will parse the date and if it finds the date to be invalid it will raise an exception.
Using Visual Studio 2008 SP1, for some reason I could not get the above to work for me. I kept getting a "String was not recognized as a valid DateTime" error message using this code: ' 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)
I found this worked for me:
I hope this helps others. It would be interesting to know why the above wouldn't work for me.
Paul
!--removed tag-->