I have to build a DropDownList with the dates of the last 7 days. I would like the DropDownList displays the date as "DD/MM/YYYY". So I created a list of dates:
DateTime date = DateTime.Now;
List<DateTime> dates = new List<DateTime>();
for (int i = 0; i < HISTORY_LENGTH; i++)
{
dates.Add(date.AddDays(-i));
}
DropDownList.DataSource = dates;
DropDownList.DataBind();
I add my dates as DateTime, not as strings. I think it is the method ToString() of my DateTime object that is called to create text that is visible in my DropDownList. By default it is the date and time. The result is:
[0]: {16/07/2008 11:08:27}
[1]: {15/07/2008 11:08:27}
[2]: {14/07/2008 11:08:27}
[3]: {13/07/2008 11:08:27}
[4]: {12/07/2008 11:08:27}
[5]: {11/07/2008 11:08:27}
[6]: {10/07/2008 11:08:27}
How can I force the format to "DD/MM/YYYY"?
Just manually add the items to the DropDownList.Items collection instead of relying on DataBind():
Instead of formatting the datasource you can also set format of the date as :
All you need to do is set
DropDownList.DataTextFormatString
- then upon DataBinding your control will apply the correct format:I would wrap the DateTime in another object and override ToString() as it is what the dropdownlist displays.
The main advantage of doing so is that you can store other information than just a string to reference other objects or data. If only a plain string is sufficient it is overkill.
If having a '/' is important for you in all locales (languages) then you have to upquote it otherwise you might end up with another character in some locates.
See http://www.color-of-code.de/index.php?option=com_content&view=article&id=58:c-format-strings&catid=38:programming&Itemid=66 for some examples (my cheat list with gotchas I ran into).
The code has to be modified a little bit:
If this is something you have to do across your entire app you need to be looking at the CultureInfo object.
You get the current CultureInfo object by calling
The
CultureInfo
object has a property calledDateTimeFormat
which in turn has a property calledShortDatePattern
which you should set like so...Now you can use that anywhere by formatting the string like so...