diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/converter/DateConverter.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/converter/DateConverter.java index 8b2dffefb..cb9bc7d04 100644 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/converter/DateConverter.java +++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/converter/DateConverter.java @@ -63,6 +63,12 @@ public Date convert(String value, Class type) { } try { + if(hasHourMinutesAndSeconds(value)){ + return getDateTimeMediumFormat().parse(value); + } + if(hasHourAndMinutes(value)){ + return getDateTimeShortFormat().parse(value); + } return getDateFormat().parse(value); } catch (ParseException pe) { @@ -73,4 +79,38 @@ public Date convert(String value, Class type) { protected DateFormat getDateFormat() { return DateFormat.getDateInstance(DateFormat.SHORT, locale); } + + protected DateFormat getDateTimeMediumFormat(){ + return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); + } + + protected DateFormat getDateTimeShortFormat(){ + return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); + } + + private boolean hasHourMinutesAndSeconds(String value){ + if( isDateTime(value) && isMediumTime(value)){ + return true; + } + return false; + } + + private boolean hasHourAndMinutes(String value){ + if( isDateTime(value) && isShortTime(value)){ + return true; + } + return false; + } + + private boolean isDateTime(String value){ + return value.split(" ").length > 1; + } + + private boolean isMediumTime(String value){ + return value.split(" ")[1].split(":").length == 3; + } + + private boolean isShortTime(String value){ + return value.split(" ")[1].split(":").length == 2; + } } diff --git a/vraptor-core/src/test/java/br/com/caelum/vraptor/converter/DateConverterTest.java b/vraptor-core/src/test/java/br/com/caelum/vraptor/converter/DateConverterTest.java index 9a9fe8bef..c2edaa6f5 100644 --- a/vraptor-core/src/test/java/br/com/caelum/vraptor/converter/DateConverterTest.java +++ b/vraptor-core/src/test/java/br/com/caelum/vraptor/converter/DateConverterTest.java @@ -80,4 +80,16 @@ public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("a,10/06/2008/a/b/c is not a valid date.")); converter.convert("a,10/06/2008/a/b/c", Date.class); } + + @Test + public void shouldBeAbleToConvertWithHourMinuteAndSecond() throws ParseException { + assertThat(converter.convert("10/06/2008 14:22:33", Date.class), is(equalTo(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss") + .parse("10/06/2008 14:22:33")))); + } + + @Test + public void shouldBeAbleToConvertWithHourAndMinute() throws ParseException { + assertThat(converter.convert("10/06/2008 14:22", Date.class), is(equalTo(new SimpleDateFormat("dd/MM/yyyy HH:mm") + .parse("10/06/2008 14:22")))); + } } \ No newline at end of file