Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Time conversion to DateConverter #1031

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ public Date convert(String value, Class<? extends Date> type) {
}

try {
if(hasHourMinutesAndSeconds(value)){
return getDateTimeMediumFormat().parse(value);
}
if(hasHourAndMinutes(value)){
return getDateTimeShortFormat().parse(value);
}
return getDateFormat().parse(value);

} catch (ParseException pe) {
Expand All @@ -73,4 +79,38 @@ public Date convert(String value, Class<? extends Date> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"))));
}
}