Here are the code I created for that purpose:
private string calculateLastUpdate(DateTime dt1, DateTime dt2)
{
string strTimeValue = "";
string timespans;
string[] arrTimespan;
TimeSpan ts = dt1.Subtract(dt2);
timespans = ts.ToString().Replace(":", ".");
if (timespans.Substring(0, 8) == "00.00.00")
timespans = timespans.Substring(9, timespans.Length - 10);
else if (timespans.Substring(0, 5) == "00.00")
timespans = timespans.Substring(6, timespans.Length - 10);
else if (timespans.Substring(0, 2) == "00")
timespans = timespans.Substring(3, timespans.Length - 10);
arrTimespan = timespans.Split('.');
strTimeValue = getTimeUnit(arrTimespan.Count(), Convert.ToInt32(arrTimespan[0]));
return strTimeValue;
}
private string getTimeUnit(int position, int value)
{
string result = "";
switch (position)
{
case 5: result= "day";
if (value / 365 >= 1)
{
result = "year";
value = value / 365;
}
else if (value / 30 >= 1)
{
result = "month";
value = value / 30;
}
else if (value / 7 >= 1)
{
result = "week";
value = value / 7;
}
break;
case 4: result = "hour"; break;
case 3: result = "minute"; break;
case 2: result = "second"; break;
case 1: result = "milisecond"; break;
}
if (value > 1)
result += "s";
result = Convert.ToString(value) + " " + result + " ago";
return result;
}
hope its usefull :)
0 comments:
Post a Comment