使用存储过程从数据库中提取数据时如何从 DateTime 中删除时间

How To Remove Time From DateTime When Pulling From Database Using Stored Procedure

我在 SQL 服务器上托管了一个数据库 table。

问题出在 'date' 类型的列上。当使用我的存储过程从数据库中提取数据时,显示日期并附加时间 12:00:00 AM。

例如,日期“30/10/2015”将作为单独的日期存储在数据库中,但是当它被添加到 gridview 时,如上所述,时间 12:00:00AM 被附加到它。我只想在 gridview 中显示日期,而不是时间。

下面是将数据从数据库绑定到 gridview 的代码:

private void BindGridEvent()
{
    string constr = System.Configuration.ConfigurationManage.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("EventInfo_CRUD"))
        {
            cmd.Parameters.AddWithValue("@Action", "SELECT");

            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = con;
                sda.SelectCommand = cmd;

                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView2.DataSource = dt;
                    GridView2.DataBind();
                }
            }
        }
    }
}

下面是用于从数据库中提取数据的存储过程:

[dbo].[EventInfo_CRUD]
      @Action VARCHAR(10)
      ,@EventID INT = NULL
      ,@Location nvarchar(MAX) = NULL
      ,@EventName nvarchar(MAX) = NULL
      ,@EventDescription nvarchar(MAX) = NULL
      ,@EventDate date = NULL
      ,@EventTime time = NULL
      ,@ImageUrl nvarchar(MAX) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    --SELECT
    IF @Action = 'SELECT'
    BEGIN
        SELECT 
            EventID,Location, EventName, EventDescription, 
            EventDate, EventTime, ImageUrl
        FROM EventInformation
    END

非常感谢大家的帮助!谢谢!

您需要指示 gridview - 或更准确地说:其中一种 BoundField 列类型 - 以特定格式显示此 .NET DateTime - 仅显示日期部分,不显示时间.

这意味着您需要手动将列添加到 gridview - 您不能在 gridview 上使用 AutoGenerateColumns

然后,对于那些有问题的列,您需要像这样设置 DataFormatString 属性:

<asp:GridView ......>
    <Columns>  
        .......
        <asp:BoundField DataField="EventDate" DataFormatString="{0:d}" />

        .......
    </Columns>
</asp:GridView ......>

{0:d} 格式字符串指示 .NET 显示此 DateTime 的 "short date format",无论您的默认日期格式样式是什么,它基本上只是年、月和日。

请参阅 MSDN documentation on the DataFormatString 了解有关您拥有的各种选项的更多详细信息

当我需要在我的 gridview 中格式化 DateTime 列时,下面的内容对我有用

<asp:BoundField DataField="TRANDATE" HeaderText="Document Date" dataformatstring="{0:MM/dd/yyyy}" htmlencode="false" />

为模板字段试试这个:

<%# Bind("Document Date", "{0:dd/MM/yyyy}") %>

如果您正在使用 asp:TemplateField,试试这个

<asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="EventDate" runat="server" Text='<%# Bind("EventDate ", "{0:d}") %>'>
        </asp:Label>
    </ItemTemplate>
</asp:TemplateField>