Here is another flavor of the same thing. The difference is you can add or set values of a calendar instance in case you needed "today". In my case I needed midnight tomorrow whenever my server starts.
Code:
public class CalendarFactoryBean extends AbstractFactoryBean {
/**
* Year; defaults to zero.
*/
private String year;
/**
* Month; defaults to zero.
*/
private String month;
/**
* Date; defaults to zero.
*/
private String dayOfMonth;
/**
* Number of hour of day (24 hour); defaults to zero.
*/
private String hourOfDay;
/**
* Number of minutes; defaults to zero.
*/
private String minute;
/**
* Number of seconds; defaults to zero.
*/
private String second;
/**
* Number of milliseconds
*/
private String milliSecond;
public void setYear(String year) {
this.year = year;
}
public void setMonth(String month) {
this.month = month;
}
public void setDayOfMonth(String dayOfMonth) {
this.dayOfMonth = dayOfMonth;
}
public void setHourOfDay(String hourOfDay) {
this.hourOfDay = hourOfDay;
}
public void setMinute(String minute) {
this.minute = minute;
}
public void setSecond(String second) {
this.second = second;
}
public void setMilliSecond(String milliSecond) {
this.milliSecond = milliSecond;
}
/**
* Overrridden
* @return
* @throws Exception
*/
@Override
protected Object createInstance() throws Exception {
Calendar calendar = Calendar.getInstance();
setValue(calendar, Calendar.YEAR, year);
setValue(calendar, Calendar.MONTH, month);
setValue(calendar, Calendar.DAY_OF_MONTH, dayOfMonth);
setValue(calendar, Calendar.HOUR_OF_DAY, hourOfDay);
setValue(calendar, Calendar.MINUTE, minute);
setValue(calendar, Calendar.SECOND, second);
setValue(calendar, Calendar.MILLISECOND, second);
return calendar.getTimeInMillis();
}
public Class getObjectType() {
return Calendar.class;
}
/**
* Helper method to either add or set the value of the date
* @param calendar The calendar instance
* @param constant The calendar field to add of set the value
* @param value The value
*/
private void setValue(final Calendar calendar, final Integer constant, final String value) {
if (calendar == null || constant == null) {
throw new IllegalArgumentException("The calendar and the constant are required");
}
if (value != null) {
if (value.contains("+") || value.contains("-")) {
String amountValue = value.substring(1);
Integer amount = Integer.parseInt(amountValue);
calendar.add(constant, amount);
} else {
Integer amount = Integer.parseInt(value);
calendar.set(constant, amount);
}
}
}
}
My Context:
Code:
<bean id="midnightTomorrow" class="com.example.CalendarFactoryBean">
<property name="dayOfMonth" value="+1" />
<property name="hourOfDay" value="0" />
<property name="minute" value="0" />
<property name="millisecond" value="0" />
</bean>