Friday, December 4, 2009

Format DateTime in Gridview.

Gridview is using mostly , now i have come up with some small but very important task on how to display Proper date time on Gridview , Basically we are defining standard date time option (date + time) , but some time we only want to display date in this case you can follow the below format.Format Date on Bound Column in Grid View

Suppose you want DOB in short date format without time , then you can simply use DataFormatString ="{0:d}" for Short Date
like this

<asp:BoundField DataField="DOB" HeaderText="DOB" DataFormatString = "{0:d}" />


if you are using above this setting then also it will not work ,coz by default the html encode is turned ON to prevent the Cross site Scripting attack , so for that you need to add one more property as HtmlEncode ="false".


<asp:BoundField DataField="DOB" HtmlEnclode="False" HeaderText="DOB" DataFormatString = "{0:d}" />

if You want Logn Date you can use - DataFormatString = "{0:D}"
if You want Logn Time you can use - DataFormatString = "{0:T}"

If you are using Template comlumn and you want to make your date string in short format then also you can use this suppose your item templates is

<ItemTemplate >
<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB") % >'> </asp:Label >
</ItemTemplate >


Then also you can use like this way:

<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB","{0:D}") % >'> </asp:Label >


Following table will show some date formating ways in Gridview column.



Format Pattern

Name

Example

d


Short date

11/8/2008

D

Long date

Sunday, August 11, 2008


t

Short time

3:32 PM

T

Long time

3:32:00 PM

f

Full date/time
(short time)

Sunday, August 11, 2008 3:32 PM

F

Full date/time
(long time)

Sunday, August 11, 2008 3:32:00 PM

g

General date/time
(short time)

8/11/2008 3:32 PM

G

General date/time
(long time)

8/11/2008 3:32:00 PM

m or M

Month day

August 11

r or R

RFC 1123


Sun, 11 Aug 2008 8:32:00 GMT

s

Sortable date/time

2008-08-11T15:32:00

u


Universable sortable date/time

2008-08-11 15:32:00z

U

Universable sortable date/time

Sunday, August 11, 2008 11:32:00 PM


y or Y

Year month

August, 2008


thanx you,

2 comments:

  1. very nice to sort out all the format pattern in one place

    ReplyDelete
  2. than you sanebond20, yes here you will get all the pattern where you can only integrate on your eval string.

    you can also use the htmlencode="false" which means the value is get HTML-encoded before they are displayed in a BoundField object

    ReplyDelete