Method to get Time elapsed with refernce to current date tim

Lakhangarg
Posted by Lakhangarg under C# category on | Views : 1743
Method to get Time elapsed with refernce to ciurrent date time.

Pass the Previous Activities DateTime. and this 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";
}
}

Comments or Responses

Login to post response