Is it possible to get the pattern string from a joda-time DateTimeFormatter?
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
String originalPattern = formatter. ???
Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well.
DateTimeFormatter is a formatter that is used to print and parse date-time objects. It has been introduced in Java 8. DateTimeFormatter is immutable and thread-safe.
So the short answer to your question is: YES (deprecated).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With