Saturday, September 24, 2011

How to Format an Eval Statement to Display a Date using Date Locale

I need to format a DateTime value that I'm using inside an ItemTemplate via an Eval expression, so it displays a short date using the locale. I tried working with the format syntax on the Eval statement without any luck.
I came across the following syntax to format an Eval expression so it displays a short date formatted according to the user's locale:

<%#((DateTime)Eval("ExpDate")).ToString("d")%>

The key is casting Eval as a DateTime which you can then convert to String. At this point you can take advantage of the ToString format "d" which uses a locale short date format.
This works for ASP.Net 2.0 and later, it will save you having to create a function to determine the users locale.
Will





1 comment: