如何在 asp.net 中默认今天的日期

How to default today's date in asp.net

我在 gridview 中有一个标签,我想将 DT 的值默认为今天的日期。我想在 gridview 2015-02-17 中这样显示。这是 gridview

内标签的 aspx
<asp:TemplateField ItemStyle-Width="150px" HeaderText="Date">
       <ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# Eval("DT")%>'></asp:Label>
   </ItemTemplate>
     </asp:TemplateField>

绑定 gridview 的代码

private void Bind_GV_Test()
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                string strQuery = "select ID, Name, Location,  DT from myTable ";
                SqlCommand cmd = new SqlCommand(strQuery);
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    gv_Test.DataSource = dt;
                    gv_Test.DataBind();
                    con.Close();
                    con.Dispose();

                }
            }
        }

将您的 sql 命令更改为

string strQuery = "select ID, Name, Location, getdate() as  DT from myTable ";

DT 将是当前日期时间。

为什么要去数据库服务器查今天的日期?

<div ID="Label1"><%=DateTime.Now.Date%></div>

如果值可以是null那么:

select ID, Name, Location, COALESCE(DT, getdate()) AS DT from myTable

你可以用ISNULL或者COALESCE来使用GETDATE如果是NULL:

string strQuery = @"SELECT ID, 
                           Name, 
                           Location,  
                           DT = ISNULL(DT, GETDATE()) 
                    FROM dbo.myTable";

如果只想显示日期部分使用

Text='<%# Bind("DT", "{0:yyyy-MM-dd}") %>'

或(强制使用当前区域性的日期格式)

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

无需更改查询的另一种选择(假设您想用今天的日期替换空日期):

Text='<%# string.Format(
              "{0:yyyy-MM-dd}",
              string.IsNullOrEmpty(Eval("DT").ToString()) ?
                  DateTime.Today : Eval("DT")) %>'