Oh Dotnet, how I hate/love thee…

September 21, 2007

I ran into another ridiculously annoying but extremely minor feature of .NET. It isn’t a bug, rather an omission. Ever tried inserting dates into an SQL Server table? It won’t accept the format ‘dd/mm/yyyy’, but will accept the format ‘yyyy-mm-dd’. Except there’s no format for ‘yyyy-mm-dd’.

So if you want to insert a date in SQL from ASP.NET, you need to use either of two methods -

DateTime dt = new DateTime();
System.Globalization.CultureInfo culture = new CultureInfo("en-AU", true);
if (txtDOB.Text.ToString() != "")
{
dt = DateTime.Parse(txtDOB.Text.ToString(), culture, DateTimeStyles.NoCurrentDateDefault);
}
string txtDate = dt.ToString("yyyy-MM-dd");
return txtDate;

Fortunately a colleague who’d been looking at the problem longer than I had found a better solution -
DateTime dte = Convert.ToDateTime(dob);
string dateText = dte.ToString("yyyyMMdd");

BTW, you can’t convert a string directly into a date format (eg. Format(”yyyyMMdd”). You have to convert the string into a date and then into the format you want. Ridiculous. I wonder what other “odd features” I’ll find in DOTNET. This is the problem with programming languages from big corporations. When one Division doesn’t talk to another, this is the result.