Is it possible to get the pattern string from a joda-time DateTimeFormatter?
DateTimeFormatter formatter = DateTimeFormat.forPattern(\"yyyyMMdd\");
String origin
Joda Time does not provide a way to get the original pattern from a DateTimeFormatter. One reason is probably that a DateTimeFormatter wasn't necessarily created from a pattern; for example DateTimeFormat.forStyle()
does not use patterns at all.
However if you always use patterns, then you could wrap the DateTimeFormat
class to record the pattern when the DateTimeFormatter
is constructed. That way you can look it up later with a simple static method. For example:
public class ReversableDateTimeFormat {
private static final Map<DateTimeFormatter, String> patternHistory = new HashMap<DateTimeFormatter, String>();
public static DateTimeFormatter forPattern(String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
patternHistory.put(dateTimeFormatter, pattern);
return dateTimeFormatter;
}
public static String getPattern(DateTimeFormatter dateTimeFormatter) {
return patternHistory.get(dateTimeFormatter);
}
}
Then you can do this:
DateTimeFormatter formatter = ReversableDateTimeFormat.forPattern("yyyyMMdd");
String originalPattern = ReverseableDateTimeFormat.getPattern(formatter);