How to format a time-stamp to show the date only i

2020-07-05 06:35发布

问题:

In an aspx page I am binding the labels like this:

  <asp:TemplateField HeaderText="Date of Joining">
            <ItemTemplate>
                <asp:Label ID="Label6" runat="server" Text='<%# Eval("date_of_joining") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Paid Priviledge Date">
            <ItemTemplate>
                <asp:Label ID="Label8" runat="server" 
                    Text='<%# Eval("paid_priviledge_date") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

And in the code behind I'm binding the grid view like this :(minimum code is given)

GridView1.DataSource = dt2;
GridView1.DataBind();

But the gridview columns show the date like this :

4/12/2011 12:00:00 AM    
4/4/2011 12:00:00 AM

Please suggest how to remove the time stamp part and to display only the date part.

I know how to do this by formatting using ToString and SubString. But I am not able to do this in gridview.

回答1:

Create a FormatDate method in your codebehind, and call that from your gridview.
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
http://www.csharp-examples.net/string-format-datetime/

This part will go in your code behind

private object FormatDate(DateTime input)
{
    return String.Format("{0:MM/dd/yy}", input);
}

And this bit will go in your markup

    <asp:TemplateField HeaderText="Date of Joining">
        <ItemTemplate>
            <asp:Label ID="Label6" runat="server" Text='<%# FormatDate(Eval("date_of_joining")) %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Paid Priviledge Date">
        <ItemTemplate>
            <asp:Label ID="Label8" runat="server" 
                Text='<%# FormatDate(Eval("paid_priviledge_date")) %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

This is what I would call a D.R.Y. approach to the problem. If you ever need to modify the formatting in any way. You can simply edit the code behind method and it will rain down sweet love to all of your markup.



回答2:

You can specify format strings for the eval statement:

Eval("date_of_joining", "{0:dd/MM/yyyy}")


回答3:

Use "{0:d}" for short date format. Try

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

and

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


回答4:

You can use the DataFormatString in a bound field the same can be set as below:

<asp:Label ID="Label8" runat="server" Text='<%# Eval("paid_priviledge_date","{0:d}") %>'/>


回答5:

Text='<%# (Convert.ToDateTime((Eval("date_of_joining")))).ToShortDateString() %>'

This is the simplest way I discovered.