0

My Desired output :

if the difference is less than a minute the result should be "Updated just now" and if the difference is than greater than a minute and less than an hour then the result should be "Updated X mintues ago"

Code:

string result = "";
if (difference.Days == 0)
{
    if (difference.Hours == 0)
    {
        if (difference.Minutes == 0)
        {
            result = "Updated just now";
        }
        else
        {
            result = "Updated " + difference.Minutes.ToString() + " minutes ago";
        }                   
    }
    else
    {
        result = "Updated " + difference.Hours.ToString() + " hours ago";
    }
}
else
{
    result = "Updated " + difference.Days.ToString() + " days ago";
}
Manivannan Nagarajan
  • 1,019
  • 1
  • 9
  • 14

2 Answers2

2
string result = "Updated ";

if (difference.Days != 0)
    result += difference.Days.ToString() + " days ago";
else if (difference.Hours != 0)
    result += difference.Hours.ToString() + " hours ago";
else if (difference.Minutes != 0)
    result += difference.Minutes.ToString() + " minutes ago";
else
    result += "just now";
Anton Kedrov
  • 1,767
  • 2
  • 13
  • 20
2
string format = "Updated {0} {1} ago";
string result = "Updated just now";
// this test can be deleted
if(difference.TotalSeconds > 60)
{
  if(difference.Days != 0)
    result = string.Format(format, difference.Days, "days");
  else if (difference.Hours != 0)
    result = string.Format(format, difference.Hours, "Hours");
  else if (difference.Minutes != 0)
    result = string.Format(format, difference.Minutes, "Minutes");
}

so that the result is cleaner, replace "days" by difference.Days > 1 ? "Days" : "Day"

the purpose of the format string, is to avoid memory leak and to allow user change text format easily and for multilang

S. Gmiden
  • 147
  • 5