While working on a project , I need to show the comments published or updated as 1 min ago, 1 Hours ago, so on. So in order to do it I had written a helper class to do it for me.
Here is the code below:
public static string GetFormattedDate(string date)
{
string formattedDate = string.Empty;
TimeSpan ts = System.DateTime.Now - DateTime.Parse(date);
int weeks = (int)(DateTime.Now - DateTime.Parse(date)).TotalDays / 7;
if (ts.Minutes == 0)
formattedDate = "Few Seconds Ago";
if (ts.Minutes > 0 && ts.Minutes < 59)
formattedDate = ts.Minutes + (ts.Minutes == 1 ? " Minute Ago" : " Minutes Ago");
if (ts.Hours > 0 && ts.Hours < 24)
formattedDate = ts.Hours + (ts.Hours == 1 ? " Hour ago" : " Hours ago");
if (ts.Days >= 1 && ts.Days<30)
{
if (ts.Days == 1)
{
formattedDate = "Today";
}
else if (ts.Days>1 && ts.Days < 7)
{
formattedDate = ts.Days + (ts.Days == 1 ? " Day ago" : " Days ago");
}
else
{
formattedDate = (ts.Days / 7).ToString() + ((ts.Days / 7).ToString() == "1" ? " Week Ago" : " Weeks Ago");
}
}
else if (ts.Days >= 30 && ts.Days<365)
{
formattedDate = ts.Days/30 + ( ts.Days<60 ? " Month ago" : " Months ago");
}
else if(ts.Days>=365)
{
formattedDate = ts.Days / 365 + ( ts.Days < 730 ? " Year ago" : " Years ago");
}
return formattedDate;
}
Here is the code below:
public static string GetFormattedDate(string date)
{
string formattedDate = string.Empty;
TimeSpan ts = System.DateTime.Now - DateTime.Parse(date);
int weeks = (int)(DateTime.Now - DateTime.Parse(date)).TotalDays / 7;
if (ts.Minutes == 0)
formattedDate = "Few Seconds Ago";
if (ts.Minutes > 0 && ts.Minutes < 59)
formattedDate = ts.Minutes + (ts.Minutes == 1 ? " Minute Ago" : " Minutes Ago");
if (ts.Hours > 0 && ts.Hours < 24)
formattedDate = ts.Hours + (ts.Hours == 1 ? " Hour ago" : " Hours ago");
if (ts.Days >= 1 && ts.Days<30)
{
if (ts.Days == 1)
{
formattedDate = "Today";
}
else if (ts.Days>1 && ts.Days < 7)
{
formattedDate = ts.Days + (ts.Days == 1 ? " Day ago" : " Days ago");
}
else
{
formattedDate = (ts.Days / 7).ToString() + ((ts.Days / 7).ToString() == "1" ? " Week Ago" : " Weeks Ago");
}
}
else if (ts.Days >= 30 && ts.Days<365)
{
formattedDate = ts.Days/30 + ( ts.Days<60 ? " Month ago" : " Months ago");
}
else if(ts.Days>=365)
{
formattedDate = ts.Days / 365 + ( ts.Days < 730 ? " Year ago" : " Years ago");
}
return formattedDate;
}
No comments:
Post a Comment