Some time ago I wrote an article about failures to properly write code concerning globalization, i.e. to write the code in such a way that it does not crash and works as intended when running in environments with regional settings you have not anticipated.
I’m playing with the wonderful N2CMS project these days. So far I’ve really enjoyed it. One of my first attempts to get known with it was to create a simple page with a date time field. They have an out-of-the-box date time control to render the field. As you can guess, I don’t have the en-US regional settings. Here’s the field:
One text box with a small nice calendar button for the date part and another text box sitting next for the time part. Let’s choose a date with the calendar.
It even recognizes the Slovak date pattern (DD. MM. YYYY):
So far so good. Let’s save the page and again open for edit. Bump:
Something very wrong happened. After some researching I found the DatePicker control’s source and there’s a quite ugly code :-):
if(value != null)
{
string[] dateTime = value.Split(' ');
DatePickerBox.Text = dateTime[0];
if (dateTime.Length > 1)
TimePickerBox.Text = dateTime[1].EndsWith(":00") ? dateTime[1].Substring(0, dateTime[1].Length - 3) : dateTime[1];
else
TimePickerBox.Text = string.Empty;
if (dateTime.Length > 2)
TimePickerBox.Text += " " + dateTime[2]; // This could be AM/PM
}
else
{
DatePickerBox.Text = string.Empty;
TimePickerBox.Text = string.Empty;
}
I don’t know the reason behind that but parsing a datetime string on your own devices is a very bad idea.
And fix is simple. Just rely on the .NET Framework to do all the magic:
if(value != null)
{
DateTime parsed;
if (DateTime.TryParse(value, out parsed))
{
DatePickerBox.Text = parsed.ToShortDateString();
if (parsed.Second == 0)
TimePickerBox.Text = parsed.ToShortTimeString();
else
TimePickerBox.Text = parsed.ToLongTimeString();
}
}
else
{
DatePickerBox.Text = string.Empty;
TimePickerBox.Text = string.Empty;
}
Disclaimer: My goal is not to whine about the N2CMS quality. No, I think that N2CMS is really a wonderful project and I’m a fan of it :-) Give it a try!