Some say that time is nothing but an illusion. The degree to which some software developers struggle with times and dates certainly suggests mysterious and unknowable forces swirling beyond the brink of human understanding. Consider this code that Ian found while pruning an old application. It's meant to provide the correct suffix for any given day of the month:
string num = "th";
int day = Convert.ToInt16(DateTime.Now.ToString("dd"));
switch(day)
{
case 1:
num = "st";
break;
case 21:
num = "st";
break;
case 31:
num = "st";
break;
case 2:
num = "nd";
break;
case 22:
num = "nd";
break;
case 3:
num = "rd";
break;
case 33:
num = "rd";
break;
default:
num = "th";
break;
}
Although the technique shown is not too far off-base, its implementation leaves something to be desired. The redundant and ultimately unused initial assignment of "th" to num
is a minor sin. Repeating identical code instead of stacking labels is another. The case to handle the 33rd of some heretofore unknown month is a somewhat more problematic problem, as it comes at the expense of an actual date, the twenty-third. But Ian's favorite gaffe was the statement Convert.ToInt16(DateTime.Now.ToString("dd"))
, which converts the current date to a string containing only the day of the month, then converts that string to an integer (no doubt converted back to a string later so num
can be attached). Had he not been sending the whole method to the bit bucket, Ian would have happily replaced that pointless convolution with DateTime.Now.Day
.
Hence today's lesson: it's always the right date to learn a little more about your chosen date/time API.