It’s a pretty common programming problem: given two dates, determine how many days are between them. Most programmers have the benefit of built-in library code, whether that’s DateTime in .NET, Calendar in Java, and so on. Some – MUMPS programmers, probably – have no choice but to parse and then re-implement the same “30 days hath September…” algorithm. And then of course there are the few who re-implement it anyway, perhaps because they figured that no one else in the history of computing had ever solved that unique problem.

But an even rarer breed are those that, like Paul’s predecessor, who to use built-in code… but from an entirely different platform. Take this method, found in production code, that inputs two dates and a TimeDifference to determine how far apart the dates are. An easy enough concept in C# that’s implemented with a trip to the database.

public static int DateDiff(DateTime date1, DateTime date2, TimeDifference td)
{
  string sql = string.Empty;

  switch (td)
  {
    case TimeDifference.Hours:
      sql = string.Format("SELECT DATEDIFF(HOUR,'{0}','{1}')", date1.ToString(), date2.ToString());
      break;
    case TimeDifference.Minutes:
      sql = string.Format("SELECT DATEDIFF(MINUTE,'{0}','{1}')", date1.ToString(), date2.ToString());
      break;
    case TimeDifference.Seconds:
      sql = string.Format("SELECT DATEDIFF(SECOND,'{0}','{1}')", date1.ToString(), date2.ToString());
      break;
    default:
      return 0;
    }

  return Convert.ToInt32(DataLayer.DataManager.executeScalar(
    sql, CommandType.Text, new NameValueCollection()));
}