TimeAgo Like facebook using asp.net c# .
Displaying date in timeago format under Listivew in Label control.
Below is the code:
<asp:ListView ID="ListView1"
ClientIDMode="Static"
runat="server"
OnItemDataBound="databound_ListView1">
<ItemTemplate>
<div class="col-sm-12">
<span class="hidden"><%# Eval("id")
%></span>
<b><%# Eval("Name") %></b>
<asp:Label ID="lbldatetime"
runat="server"
text='<%# Eval("DateTime") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:ListView>
aspx.cs code
public static string TimeAgo(DateTime
date)
{
TimeSpan timeSince = DateTime.Now.Subtract(date);
if (timeSince.TotalMilliseconds < 1)
return "not
yet";
if (timeSince.TotalMinutes < 1)
return "just
now";
if (timeSince.TotalMinutes < 2)
return "1
minute ago";
if (timeSince.TotalMinutes < 60)
return string.Format("{0} minutes ago", timeSince.Minutes);
if (timeSince.TotalMinutes < 120)
return "1
hour ago";
if (timeSince.TotalHours < 24)
return string.Format("{0} hours ago", timeSince.Hours);
if (timeSince.TotalDays == 1)
return "yesterday";
if (timeSince.TotalDays < 7)
return string.Format("{0} days ago", timeSince.Days);
if (timeSince.TotalDays < 14)
return "last
week";
if (timeSince.TotalDays < 21)
return "2
weeks ago";
if (timeSince.TotalDays < 28)
return "3
weeks ago";
if (timeSince.TotalDays < 60)
return "last
month";
if (timeSince.TotalDays < 365)
return string.Format("{0} months ago", Math.Round(timeSince.TotalDays / 30));
if (timeSince.TotalDays < 730)
return "last
year";
//last but
not least...
return string.Format("{0} years ago", Math.Round(timeSince.TotalDays / 365));
}
protected void
databound_ListView1(object sender, ListViewItemEventArgs e)
{
Label dt;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
dt = (Label)e.Item.FindControl("lbldatetime");
DateTime date = Convert.ToDateTime(dt.Text);
string b = TimeAgo(date);
dt.Text = b;
}
}
OUTPUT
Thanks for sharing.
ReplyDelete