Last active
June 10, 2016 14:44
-
-
Save fre-sch/6fefb22481d90eb52261 to your computer and use it in GitHub Desktop.
Parse multiple date string formats
This file contains 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.DateFormat | |
import java.text.FieldPosition | |
import java.text.NumberFormat | |
import java.text.ParsePosition | |
import java.text.SimpleDateFormat | |
class MultiDateFormat extends DateFormat { | |
private final SimpleDateFormat printer | |
private final List<SimpleDateFormat> parsers | |
MultiDateFormat( | |
String printFormat, List<String> readFormats) { | |
super() | |
calendar = Calendar.instance | |
numberFormat = NumberFormat.instance | |
printer = new SimpleDateFormat(printFormat) | |
parsers = readFormats.collect { new SimpleDateFormat(it) } | |
} | |
@Override | |
StringBuffer format( | |
Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { | |
printer.format(date, toAppendTo, fieldPosition) | |
} | |
@Override | |
Date parse(String source, ParsePosition pos) { | |
parsers.findResult { it.parse(source, pos) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment