LocaleBasedDateConverter implements Converter<Date> { public Date convert(String value, Class<? extends Date> type, ResourceBundle bundle) { if (isNullOrEmpty(value)) { return null; } Locale locale = localization.getLocale(); if (locale == null) { locale = Locale.getDefault(); } DateFormat formatDateTime = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.MEDIUM, locale); try { return formatDateTime.parse(value); } catch (ParseException pe) { DateFormat formatDate = DateFormat.getDateInstance( DateFormat.SHORT, locale); try { return formatDate.parse(value); } catch (ParseException pe1) { throw new ConversionError(MessageFormat.format( bundle.getString("is_not_a_valid_date"), value)); } } } LocaleBasedDateConverter(Localization localization); Date convert(String value, Class<? extends Date> type, ResourceBundle bundle);  }
@Test public void shouldBeAbleToConvert() throws ParseException { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn("pt_br"); assertThat(converter.convert("10/06/2008", Date.class, bundle), is(equalTo(new SimpleDateFormat("dd/MM/yyyy") .parse("10/06/2008")))); }
@Test public void shouldUseTheDefaultLocale() throws ParseException { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn(null); when(request.getSession()).thenReturn(session); when(session.getAttribute(LOCALE_KEY + ".session")). thenReturn(null); when(context.getAttribute(LOCALE_KEY + ".application")). thenReturn(null); when(context.getInitParameter(LOCALE_KEY)). thenReturn(null); when(request.getLocale()).thenReturn(null); Date date = new SimpleDateFormat("dd/MM/yyyy").parse("10/05/2010"); String formattedToday = DateFormat.getDateInstance(DateFormat.SHORT).format(date); assertThat(converter.convert(formattedToday, Date.class, bundle), is(equalTo(date))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Date.class, bundle), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Date.class, bundle), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn("pt_br"); try { converter.convert("a,10/06/2008/a/b/c", Date.class, bundle); } catch (ConversionError e) { assertThat(e.getMessage(), is(equalTo("a,10/06/2008/a/b/c is not a valid date."))); } }