Last active
December 16, 2015 12:49
-
-
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
This file contains hidden or 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
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