Possible Duplicate:
How do I calculate relative time?
While posting something on SO it shows posted 5 mins ago
or 1hr ago
. How do I calculate the time and display it the same way?
asked Sep 6, 2011 at 11:42
-
@Daniel - I need the logic to try. I am not asking for code am just asking for hint to get started.Mal– Mal2011年09月06日 11:46:59 +00:00Commented Sep 6, 2011 at 11:46
-
this could get you going: stackoverflow.com/questions/842057/…Peter– Peter2011年09月06日 11:47:24 +00:00Commented Sep 6, 2011 at 11:47
-
You can take 2 DateTime instances and subtract them like this: TimeSpan result = firstDateTimeInstance - secondDateTimeInstance;Icarus– Icarus2011年09月06日 11:50:26 +00:00Commented Sep 6, 2011 at 11:50
1 Answer 1
For example C# Pretty Date Formatting:
static string GetPrettyDate(DateTime d)
{
// 1.
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// 2.
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0 || dayDiff >= 31)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return null;
}
(And you can also use a jquery plugin named Prettydate.)
answered Sep 6, 2011 at 11:49
Sign up to request clarification or add additional context in comments.
Comments
default