Pattern String from a joda-time DateTimeFormatter?

寵の児 提交于 2019-12-31 21:43:11

问题


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

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
String originalPattern = formatter. ???

回答1:


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);


来源:https://stackoverflow.com/questions/10490951/pattern-string-from-a-joda-time-datetimeformatter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!