Created
April 27, 2012 18:08
-
-
Save lucascs/2511422 to your computer and use it in GitHub Desktop.
Calendar converter for date and time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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