Ruan
Ruan

Reputation: 4293

Change date Format or String length of lable ItemTemplate

Is there a way to format the text I get from my dataset (which is a date type) to not show time.

I had it in my sql query to format the date to not show time, but then I had to change it into a string and I need the datatype to still be a Date.

So I cant user This any more...

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

And this doesn't work

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

Here is my Template.

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

Is there a way to maybe modify the template to cut out the Time of the date?

Upvotes: 0

Views: 5564

Answers (4)

user16910095
user16910095

Reputation: 1

You can use

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

Upvotes: 0

Hugo Meneses
Hugo Meneses

Reputation: 11

<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>

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460238

Yes, you can use ToShortDateString:

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

or

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

Standard Date and Time Format Strings

Or use RowDataBound (assuming GridView, works also in other webdatabound controls like Repeater with ItemDataBound event):

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");
    }
}

Upvotes: 6

yoozer8
yoozer8

Reputation: 7489

You can parse the string as a DateTime, and use the ToString method to format it without the time.

Depending on the format you want, you would do something like

myDateTime.ToString("d MMM yyy");

Upvotes: -1

Related Questions