【问题标题】:Change date Format or String length of lable ItemTemplate更改标签 ItemTemplate 的日期格式或字符串长度
【发布时间】:2013-04-20 15:21:42
【问题描述】:

有没有办法将我从数据集(日期类型)中获得的文本格式化为不显示时间。

我在我的 sql 查询中使用它来格式化日期以不显示时间,但后来我不得不将它更改为字符串,并且我需要数据类型仍然是日期。

所以我不能再使用这个了...

CONVERT(varchar(15),em.endDate,111) as endDate --> 2001/05/05

这不起作用

CONVERT(Date,em.endDate,111) --> 输出:输出:5/5/2001 12:00:00 AM

这是我的模板。

 <asp:TemplateField HeaderText="endDate" SortExpression="endDate">
     <ItemTemplate>
         <asp:Label ID="lblEndDate" runat="server" Text='<%# Bind("endDate") %>'></asp:Label>
     </ItemTemplate>
 </asp:TemplateField>

有没有办法修改模板以删除日期时间?

【问题讨论】:

    标签: c# asp.net sql date


    【解决方案1】:

    你可以使用

    <asp:Label ID="lblEndDate" runat="server" Text='<%#Eval("EndDate","{0: dd- MMM - yyyy}")%>' />
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:
    <asp:TemplateField SortExpression="MyDate"  HeaderText="MyDate">
        <ItemTemplate>
            <asp:Label ID="lblMyDate" runat="server"
                Text='<%# Eval("MyDate", "{0:dd/MM/yyyy}") %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    

    【讨论】:

      【解决方案3】:

      是的,你可以使用ToShortDateString

      Text='<%# ((DateTime)Eval("endDate")).ToShortDateString() %>'
      

      Text='<%#Eval("endDate","{0:d}")%>'
      

      Standard Date and Time Format Strings

      或使用RowDataBound(假设GridView,也适用于其他webdatabound控件,如带有ItemDataBound事件的Repeater):

      protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
              DataRow row = ((DataRowView)e.Row.DataItem).Row; // you might use a different datasource, use the debugger if you are unsure
              Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
              lblEndDate.Text = row.Field<DateTime>("endDate").ToString("d");
          }
      }
      

      【讨论】:

      • 当 Eval("endDate") 为 DBNull 时要小心。
      • 就我而言,因为“created”可以为空,所以我在转换为 DateTime 之前进行了检查,如下所示
      【解决方案4】:

      您可以将字符串解析为DateTime,并使用ToString方法将其格式化,无需时间。

      根据您想要的格式,您可以执行类似的操作

      myDateTime.ToString("d MMM yyy");
      

      【讨论】:

        猜你喜欢
        • 2016-06-25
        • 1970-01-01
        • 2011-05-04
        • 2022-07-04
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2021-05-07
        相关资源
        最近更新 更多