
.NET 2.0+Displaying Relative Time (2)
When developing software that works with time stamped information, it is common to show the date and time at which an item was created or last updated. A user-friendly alternative is to display a relative time, such as "Two Hours Ago".
Getting the Time Offset
Obtaining the time offset is achieved using an if-else-if ladder. Each if statement checks if the TimeSpan is greater than or equal to a cut-off value. If it is, the GetOffSetWords method is called to obtain the result using a specified unit of time. The ladder starts with the largest duration and finishes with the smallest. This allows the use of one predicate per condition only as the upper bound of a range is implicitly set by the previous condition.
private string GetOffset(TimeSpan positive)
{
if (positive.Days >= 365)
return GetOffsetWords(positive.Days / 365, "Year");
else if (positive.Days >= 7)
return GetOffsetWords(positive.Days / 7, "Week");
else if (positive.Days >= 1)
return GetOffsetWords(positive.Days, "Day");
else if (positive.Hours >= 1)
return GetOffsetWords(positive.Hours, "Hour");
else if (positive.Minutes >= 1)
return GetOffsetWords(positive.Minutes, "Minute");
else
return GetOffsetWords(positive.Seconds, "Second");
}
The GetOffSetWords method builds the duration string from the offset value and unit. The offset value is converted into a string using the NumberToWordsConverter class and the unit is appended. If the number is not one, an "s" is added to the unit to avoid results such as "One Seconds" or "Two Minute".
private string GetOffsetWords(int offset, string unit)
{
string offsetWords = new NumberToWordsConverter().NumberToWords(offset);
if (offset != 1) unit += "s";
return string.Format("{0} {1}", offsetWords, unit);
}
Getting the Suffix
The final private method obtains a suffix for the time offset. This method simply determines whether the difference between the current and provided times is positive or negative. If positive, the suffix is "Ago". If negative, the suffix is "in the Future".
private string GetSuffix(TimeSpan difference)
{
return difference.TotalSeconds > 0 ? "Ago" : "in the Future";
}
You can now test the class by calling it from the Main method of the console application. Try using different past and future dates to see the results. You can also download the demo application from the link at the top of the page. This is a Windows Forms program that allows you to specify a date and time and see the relative time produced.
14 February 2010