Skip to content

Instantly share code, notes, and snippets.

@lucascs
Created April 27, 2012 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucascs/2511422 to your computer and use it in GitHub Desktop.
Save lucascs/2511422 to your computer and use it in GitHub Desktop.
Calendar converter for date and time
@Convert(Calendar.class)
public class DateAndTimeCalendarConverter extends LocaleBasedCalendarConverter {
private final Localization localization;
public DateAndTimeCalendarConverter(Localization localization) {
super(localization);
this.localization = localization;
}
public Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle) {
if (Strings.nullToEmpty(value).length() > "dd/mm/yyyy".length()) {
Locale locale = localization.getLocale();
if (locale == null) {
locale = Locale.getDefault();
}
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, locale);
try {
Date date = format.parse(value);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar;
} catch (ParseException e) {
throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_date"), value));
}
}
return super.convert(value, type, bundle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment