来自joda-time DateTimeFormatter的模式字符串? [英] Pattern String from a joda-time DateTimeFormatter?

查看:60
本文介绍了来自joda-time DateTimeFormatter的模式字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从joda-time DateTimeFormatter获取模式字符串?

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

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

推荐答案

Joda Time无法提供从DateTimeFormatter获取原始模式的方法.原因之一可能是DateTimeFormatter不一定是从模式创建的.例如DateTimeFormat.forStyle()根本不使用模式.

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.

但是,如果您始终使用模式,则可以包装DateTimeFormat类以在构造DateTimeFormatter时记录模式.这样,您以后可以使用简单的静态方法进行查找.例如:

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

这篇关于来自joda-time DateTimeFormatter的模式字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆