Convert datetime to dd/MM/yyyy

Asked

Viewed 3,496 times

8

I have a Gridview and I’m using Templatefield to display the date that is currently in the format `string yyyy-MM-dd 00:00:00.

I need to show this date with dd/MM/yyyy. I’ve tried to use {0:dd/MM/yyyy} and it doesn’t work. Can someone help me ?

  • What shape is it in? yyyy-mm-dd hh:mm:ss.mmm?

  • I’m converting to string at a time so it comes "dd/MM/yyyy 00:00:00", but I need it to display only dd/MM/yyyyy.

1 answer

4

The following code correctly formats the date, confirm that your code is equivalent:

<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# DataBinder.Eval(Container.DataItem, "data_inicio", "{0:dd/MM/yyyy}")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

After receiving some more information per comment, I learned that the property used in the grid column is not of the Datetime type. In order to appear with the desired format, you will need to convert to Datetime and then format again as string:

<ItemTemplate>
    <%# Convert.ToDateTime(Eval("Data")).ToString("dd/MM/yyyy")%>
</ItemTemplate>

But I suggest you do not convert the property to string and send the DateTime to the Grid.

  • Dude, it didn’t work. I need to call something on the page to read this Databinder ?

  • Today it looks like this, <Asp:Templatefield Headertext="Start Date"> <Itemtemplate> <%# Eval("start_date", "{0:dd/MM/yyyy}")%> </Itemtemplate> </Asp:Templatefield>

  • Your code is right too, Eval with the arguments you are passing are correct. Make sure the property data_inicio is the type DateTime?

  • No, the start date property is string. Here I am converting to do the search for what the database accepts which is yyyyyy-MM-dd.

  • It will not roll then, this format string "dd/MM/yyyy" only Datetime understands. I suggest editing your question to include the information that is working with a string on the grid and not with Datetime.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.