如何在转发器的标签中显示时间

时间:2013-09-05 18:37:49

标签: c# asp.net repeater

我有一个文章表,这个表包含一个名为“dateofSubmitArticle”的字段 当我在转发器中显示我希望在标签中显示的文章时,这篇文章在数据库中提交了多少时间 转发器的数据源是

 var n = (from a in DataContext.Context.Articles
                 join u in DataContext.Context.Users
                 on a.UserID equals u.UserID
                 orderby a.ArticleID descending
                 where a.IsConfirmByAdmin == true
                 select new { 
                 ArticleID=a.ArticleID,
                 ArticleTitle=a.ArticleTitle,
                 ArticleSummery=a.ArticleSummery,
                 SubmitDate=a.SubmitDate,
                 Username=u.Username,
                 ArticleImageName=a.ArticleImageName
                 }).Take(15);
        rptArticleTitle.DataSource = n;
        rptArticleTitle.DataBind();

1 个答案:

答案 0 :(得分:0)

您可以使用Timespan类。为了实现您的目标,在转发器中放置一个asp标签和隐藏字段,将SubmitDate绑定到该隐藏字段。

HTML:

<asp:Label runat="server" id="Submitted" />
<asp:Hidden runat="server" id="val" Value='<%#Eval("SubmitDate")%>'/>

现在在转发器中ItemDataBound找到标签并隐藏并使用下面的代码。

void ItemDataBound()
{
  if(e.Item.ItemType == DataItemType || e.Item.ItemType ==AlternatingItemType)
  {
      var lbl = e.Item.FindControl(lable_id) as Label;
      var hid = e.Item.FindControl(hidden_id) as Hidden;

      if(lbl !=null and hid !=null)
      {
          var val = DateTime.Parse(hid.Value);
         // Get the TimeSpan of the difference. 
         TimeSpan elapsed = now.Subtract(val); 
         lbl.Text = string.Format("{0} days ago", elapsed.Days);
      }

  }
}