java 来自 joda 时间 DateTimeFormatter 的模式字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10490951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pattern String from a joda-time DateTimeFormatter?
提问by Synesso
Is it possible to get the pattern string from a joda-time DateTimeFormatter?
是否可以从 joda-time DateTimeFormatter 获取模式字符串?
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
String originalPattern = formatter. ???
回答by gutch
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.
Joda Time 不提供从 DateTimeFormatter 获取原始模式的方法。一个原因可能是 DateTimeFormatter 不一定是从模式创建的;例如DateTimeFormat.forStyle()
根本不使用模式。
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:
但是,如果您总是使用模式,那么您可以包装DateTimeFormat
类以在DateTimeFormatter
构造时记录模式。这样你以后就可以用一个简单的静态方法来查找它。例如:
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);