views:

119

answers:

3

Possible Duplicates:
Fuzzy date algorithm
How do I calculate relative time?

Hi,

How-to format datetime like SO ?

1 minute ago

1 hour ago

asked Aug 15 at 15:00

+1  A: 

You may interest to port jQuery's timeago plugin to C#

S.Mark
A: 

Check out DateTime.ToString() Patterns. If there isn't anything you like, you can specify it yourself.

Ian
+1  A: 

First thing you need to do is determine the difference in dates.

Use the Subtract() method on your DateTime. It returns a TimeSpan, which is handy for your needs.

TimeSpan mySpan = DateTime.Now.Subtract( myPostedDate );

Then, you'll need to find the most significant non-zero time element. If you're dealing with days, things are easy. Smaller denominations require a little more work. Code included.

TimeSpan mySpan = DateTime.Now.Subtract(myRecorded);
string  myDenom = 
  mySpan.Days    > 0 ? "day" : 
  mySpan.Hours   > 0 ? "hour" : 
  mySpan.Minutes > 0 ? "minute" : "second";

string myOutput = String.Empty;

int myNumeral;

// if we're dealing with days, a format string will suffice
if (myDenom == "day")
{
    // HH - 24 hour clock
    myOutput = String.Format("{0:MMM dd} at {0:HH}:{0:mm}", myRecorded);
}
else
{
    // put the right denomination into myNumeral
    switch (myDenom)
    {
        case "second":
            myNumeral = mySpan.Seconds;
            break;
        case "minute":
            myNumeral = mySpan.Minutes;
            break;
        default:
            myNumeral = mySpan.Hours;
            break;
    }

    // add an s to myNumeral when > 1
    myDenom += (myNumeral > 1) ? "s" : String.Empty;
    myOutput = String.Format("{0} {1} ago", myNumeral, myDenom);
}

// myOutput now contains formatted string
Paul Alan Taylor