I have this as part of a project to normalize DateTime
values to more readable strings, localized to the relative time in the past that they happened.
It allows you to make several customizations. If you don't want a time to show up, specify ""
for the timeFormat
, etc. You can change the reference DateTime
so that you can measure values between any two DateTime
points.
The idea is to put them in forms like:
Event happened just now
Event happened 29 minutes ago
Event happened yesterday at 3:54 pm
etc
I'm looking for any and all improvements (as per the standard rules).
I assume my use of optional
statements is less than idea, but I'm open to any and all suggestions about everything here.
public static string ToNormalizedString(this DateTime DateTime, DateTime? reference = null, string dateFormat = "MMM d, yyyy", string timeFormat = "h:mm tt", string preDateString = "", string preTimeString = "at", bool capitalizeModifiers = true)
{
string result = "";
DateTime referenceDateTime = DateTime.UtcNow;
if (reference.HasValue)
{
referenceDateTime = reference.Value;
}
if (DateTime.Date == referenceDateTime.Date)
{
TimeSpan TimeDifference = referenceDateTime - DateTime;
if (TimeDifference < new TimeSpan(0, 1, 0))
{
result = (capitalizeModifiers ? "Just now" : "just now");
}
else if (TimeDifference < new TimeSpan(0, 2, 0))
{
result = (capitalizeModifiers ? "About a minute ago" : "about a minute ago");
}
else if (TimeDifference < new TimeSpan(1, 0, 0))
{
result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalMinutes).ToString() + " minutes ago";
}
else
{
result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalHours).ToString() + " hours ago";
}
}
else if (DateTime.Date.AddDays(1) == referenceDateTime.Date)
{
result = (capitalizeModifiers ? "Yesterday at " : "yesterday at ") + DateTime.ToString(timeFormat);
}
else if (DateTime.Date.AddDays(7) > referenceDateTime.Date)
{
result = preDateString + DateTime.DayOfWeek.ToString() + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
}
else
{
result = preDateString + DateTime.ToString(dateFormat) + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
}
return result;
}
As usual this code is free to anyone who wishes to use it.