Tuesday, July 22, 2008

Time Ago in Words for .NET C#

I saw the need for a C# version of the time_ago_in_words function in Ruby. I translated the code below into C# from my existing post I published for Ruby.





static string TimeAgo(DateTime time)
{
DateTime startDate = DateTime.Now;
TimeSpan deltaMinutes = startDate.Subtract(time);
string distance = string.Empty;
if (deltaMinutes.TotalMinutes <= (8724 * 60))
{
distance = DistanceOfTimeInWords(deltaMinutes.TotalMinutes);
if (deltaMinutes.Minutes < 0)
{
return distance + " from now";
}
else
{
return distance + " ago";
}
}
else
{
return "on " + time.ToString();
}
}


static string DistanceOfTimeInWords(double minutes)
{
if (minutes < 1)
{
return "less than a minute";
}
else if (minutes < 50)
{
return minutes.ToString() + " minutes";
}
else if (minutes < 90)
{
return "about one hour";
}
else if (minutes < 1080)
{
return Math.Round(new decimal((minutes / 60))).ToString() + " hours";
}
else if (minutes < 1440)
{
return "one day";
}
else if (minutes < 2880)
{
return "about one day";
}
else
{
return Math.Round(new decimal((minutes / 1440))).ToString() + " days";
}
}




You can download the complete source here: http://www.box.net/shared/3fmhllxq8g

1 comment:

  1. Awesome stuff buddy. However I had to replace

    return minutes.ToString() + " minutes";

    with

    return minutes.ToString("#0") + " minutes";

    ReplyDelete