Method to Get Time Elapsed With Refernce to Current Date Time

Lakhangarg
Posted by Lakhangarg under ASP.NET category on | Views : 1837
With the help of following code we can get the time elapsed with refernce to current date time.

Pass the Previous Activities Date Time and the following function will return time elapsed in the format:
{Number} hour/hours ago,{Number} Day/Days ago,{Number} week/weeks ago,{Number} month/months ago

public static string GetDaysAgo(string strCreatedDateTime)
{
try
{
DateTime CreatedDateTime = Convert.ToDateTime(strCreatedDateTime);
string StrReturn = null;
TimeSpan TimeDiff = DateTime.Now - CreatedDateTime;
double MinDiff = Convert.ToDouble(TimeDiff.TotalMinutes.ToString());
if (MinDiff < 0) MinDiff = 0;
if (MinDiff < 60) StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " minutes ago";
else { MinDiff = MinDiff / 60;
if (MinDiff < 24) if (Math.Floor(Convert.ToDecimal(MinDiff)) == 1) StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " hour ago";
else StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " hours ago";
else { MinDiff = MinDiff / 24;
if (MinDiff < 7) if (Math.Floor(Convert.ToDecimal(MinDiff)) == 1) StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " day ago";
else StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " days ago";
else if (MinDiff < 30) { MinDiff = MinDiff / 7;
if (Math.Floor(Convert.ToDecimal(MinDiff)) == 1) StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " week ago";
else StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " weeks ago";
} else { MinDiff = MinDiff / 30;
if (Math.Floor(Convert.ToDecimal(MinDiff)) == 1) StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " month ago";
else StrReturn = Math.Floor(Convert.ToDecimal(MinDiff)).ToString() + " months ago";
} } } return StrReturn;
} catch (Exception ex) { return "1 months ago";
} }


Call this function like this:
GetDaysAgo("30/8/2009");

Comments or Responses

Login to post response