Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern String from a joda-time DateTimeFormatter?

Tags:

java

jodatime

Is it possible to get the pattern string from a joda-time DateTimeFormatter?

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
String originalPattern = formatter. ???
like image 676
Synesso Avatar asked May 08 '12 00:05

Synesso


People also ask

Is org Joda time format DateTimeFormatter thread-safe?

Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well.

Is DateTimeFormatter Ofpattern thread-safe?

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.

Is Joda time deprecated?

So the short answer to your question is: YES (deprecated).


1 Answers

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);
like image 134
gutch Avatar answered Oct 20 '22 09:10

gutch