Tuesday, April 28, 2009

Sample JSP Date Combo

This method produces required html code for date time combos. Date parameter is selected in case of equality.

public static String printDateCombos(String name , java.util.Date date) {
Calendar today = Calendar.getInstance(new Locale("en-US")) ;
if (date == null)
today.setTimeInMillis( System.currentTimeMillis() );
else
today.setTime( date ) ;
int year = today.get( Calendar.YEAR );
int month = today.get( Calendar.MONTH );
int day = today.get( Calendar.DAY_OF_MONTH );
int hour = today.get( Calendar.HOUR_OF_DAY );
int min = today.get( Calendar.MINUTE );
StringBuffer out = new StringBuffer();
out.append("<select name=\"");
out.append(name);
out.append("_day\">");
for (int i=1;i<32;i++) {
out.append("<option");
if (i==day) out.append(" selected ");
out.append(">");
if (i<10) out.append('0');
out.append(i);
out.append("</option>");
}
out.append("</select>");
// month
out.append("/<select name=\"");
out.append(name);
out.append("_month\">");
for (int i=0;i<12;i++) {
out.append("<option");
if (i==month) out.append(" selected");
out.append(" value=");
out.append(i+1);
out.append(">");
out.append( MONTHS[i] );
out.append("</option>");
}
out.append("</select>");
// year
out.append("/<select name=\"");
out.append(name);
out.append("_year\">");
for (int i=0;i<10;i++) {
out.append("<option");
if (i==0) out.append(" selected");
out.append(">");
out.append(year+i);
out.append("</option>");
}
out.append("</select>");
// hour
out.append("-<select name=\"");
out.append(name);
out.append("_hour\">");
for (int i=0;i<24;i++) {
out.append("<option");
if (i==hour) out.append(" selected");
out.append(">");
if (i<10) out.append('0');
out.append(i);
out.append("</option>");
}
out.append("</select>:");
// minute
out.append("<select name=\"");
out.append(name);
out.append("_minute\">");
for (int i=0;i<60;i++) {
out.append("<option");
if (i==min) out.append(" selected");
out.append(">");
if (i<10) out.append('0');
out.append(i);
out.append("</option>");
}
out.append("</select>");
return out.toString() ;
}

0 nhận xét: