import java.util.*;
public class DatePulldown
{
private StringBuffer Buffer = new StringBuffer();
private Calendar Cal = new GregorianCalendar();
public void setDate(Date date)
{
Cal.setTime(date);
}
public String toString()
{
Render();
return Buffer.toString();
}
protected void Render()
{
Buffer.append(CreateMonthList(Cal.get(Calendar.MONTH)));
// Make day value zero-based.
Buffer.append(CreateDayList(Cal.get(Calendar.DAY_OF_MONTH)));
Buffer.append(CreateYearList(Cal.get(Calendar.YEAR)));
}
protected String CreateMonthList(int givenMonth)
{
// Create a pulldown of months.
// Select the given month from the list.
StringBuffer monthList = new StringBuffer();
monthList.append("<SELECT NAME=\"month\">\n");
for(int i = Calendar.JANUARY; i <= Calendar.DECEMBER; i++)
{
monthList.append("<OPTION");
if(givenMonth == i)
{
// If a month was specified, select it in the list.
monthList.append(" SELECTED");
}
monthList.append(">");
monthList.append(i + 1); // Shift to 1-based counting.
monthList.append("</OPTION>\n");
}
monthList.append("</SELECT>\n");
return monthList.toString();
}
protected String CreateDayList(int givenDay)
{
// Create a pulldown of days of the month.
// Select the given day from the list.
StringBuffer dayList = new StringBuffer();
dayList.append("<SELECT NAME=\"day\">\n");
// Note that some months have fewer than 31 days, but because
// the pulldowns are dynamic, there is no way to customize
// that here. We'll sanity-check the user's input later.
for(int i = 1; i < 32; i++)
{
dayList.append("<OPTION");
if(givenDay == i)
{
// If a day was specified, select it in the list.
dayList.append(" SELECTED");
}
dayList.append(">");
dayList.append(i);
dayList.append("</OPTION>\n");
}
dayList.append("</SELECT>\n");
return dayList.toString();
}
protected String CreateYearList(int givenYear)
{
// Create a pulldown of years. The years pulldown should go
// back 99 years. If a year is given, select it.
StringBuffer yearList = new StringBuffer();
yearList.append("<SELECT NAME=\"year\">\n");
Calendar now = new GregorianCalendar();
int endYear = now.get(Calendar.YEAR);
int startYear = (endYear - 99);
for(int i = startYear; i <= endYear; i++)
{
yearList.append("<OPTION");
if(givenYear == i)
{
// If a day was specified, select it in the list.
yearList.append(" SELECTED");
}
yearList.append(">");
yearList.append(i);
yearList.append("</OPTION>\n");
}
yearList.append("</SELECT>\n");
return yearList.toString();
}
}
End of Listing