Skip to content

Instantly share code, notes, and snippets.

@fre-sch
Last active June 10, 2016 14:44
Show Gist options
  • Save fre-sch/6fefb22481d90eb52261 to your computer and use it in GitHub Desktop.
Save fre-sch/6fefb22481d90eb52261 to your computer and use it in GitHub Desktop.
Parse multiple date string formats
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