Skip to content

Instantly share code, notes, and snippets.

@mdread
Last active December 16, 2015 12:49
Show Gist options
  • Save mdread/5437499 to your computer and use it in GitHub Desktop.
Save mdread/5437499 to your computer and use it in GitHub Desktop.
convert between string rappresentations of dates. example: from("yyyy-MM-dd").to("dd/MM/yyyy").convert("1987-12-01"); // results in 01/12/1987
import java.text.ParseException;
import java.text.SimpleDateFormat;
public final class DateConverter {
private SimpleDateFormat formatterFrom;
private SimpleDateFormat formatterTo;
private DateConverter(){
super();
}
public static DateConverter from(String pattern){
DateConverter converter = new DateConverter();
converter.formatterFrom = new SimpleDateFormat(pattern);
return converter;
}
public DateConverter to(String pattern){
formatterTo = new SimpleDateFormat(pattern);
return this;
}
public String convert(String date) {
if(formatterTo == null || formatterFrom == null)
throw new RuntimeException("DateFormatter is not ready to format!");
try {
return formatterTo.format(formatterFrom.parse(date));
} catch (ParseException e) {
throw new RuntimeException(e.getCause());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment