The following method is used in a call center application to display an approximation of remaining time. The call center telephone operator would inform the caller that they could perform their desired action (like, for example, place another order) after N time has elapsed. You'll note some arbitrary rules revolving around the interpretation of time embedded within the method, e.g., an interval greater than 50 minutes is considered to be "1 hour"; these business rules need to remain as is.
With that in mind, are there any suggestions on how this routine might be enhanced and/or improved (i.e., made more efficient)?
N.B. Obviously, the millisecond case (the "else") is not practical, but only included now for the sake of completeness. It may, in the end, be converted to something like 'less than 3 seconds' equals "now". For the sake of this question, however, let's go with the routine as written.
public static string LargestIntervalWithUnits(TimeSpan interval)
{
if (interval < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException("interval");
}
if (interval == TimeSpan.Zero)
{
return "now";
}
int timeValue;
string timeUnits;
if (interval.TotalHours > 22.0)
{
timeValue = (int)Math.Ceiling(interval.TotalDays);
timeUnits = " day";
}
else if (interval.TotalMinutes > 50.0)
{
timeValue = (int)Math.Ceiling(interval.TotalHours);
timeUnits = " hour";
}
else if (interval.TotalSeconds > 40.0)
{
timeValue = (int)Math.Ceiling(interval.TotalMinutes);
timeUnits = " minute";
}
else if (interval.TotalMilliseconds > 500.0)
{
timeValue = (int)Math.Ceiling(interval.TotalSeconds);
timeUnits = " second";
}
else
{
timeValue = (int)Math.Ceiling(interval.TotalMilliseconds);
timeUnits = " millisecond";
}
return string.Format("{0:#,##0}{1}{2}",
timeValue,
timeUnits,
(timeValue == 1 ? string.Empty : "s"));
}
Edit: Subsequent refactored code block, that was added after answers were posted, has been removed per users' suggestions. (This note has been added to clarify comments posted by users.)
Edit 2: The code listed above has been refactored and reposted for further review: Displaying TimeSpan as largest interval (with units) [Part II]