Pattern String from a joda-time DateTimeFormatter?

前端 未结 1 1327
清歌不尽
清歌不尽 2021-02-05 10:55

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

DateTimeFormatter formatter = DateTimeFormat.forPattern(\"yyyyMMdd\");
String origin         


        
相关标签:
1条回答
  • 2021-02-05 11:40

    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);
    
    0 讨论(0)
提交回复
热议问题