Get original pattern String given a JDK 8 DateTimeFormatter?

旧街凉风 提交于 2019-12-28 03:04:28

问题


Related to my question here - how do I get the original pattern String given a DateTimeFormatter?


回答1:


It's been asked on the mailing list and the answer is that it is not possible because the original pattern is not retained.

The same thread suggests using a DateTimeFormatterBuilder which does have the information.




回答2:


It may not be a direct answer to your question but it may help.

If you know the parameters of how it the formatter was constructed you can call the static method:

DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle, Chronology chrono, Locale locale)

This will give you the pattern as a string.




回答3:


Not a straightforward or elegant solution, but using the results of the DateTimeFormatter's .toString() method, it might be possible to roll your own code that parses out the resulting String and reconstructs the original pattern.

Some code that prints a few .toString() results for various patterns:

java.time.format.DateTimeFormatter variousFormatPatterns =
    java.time.format.DateTimeFormatter.ofPattern("yy MM dd");
System.out.println("Test 1: " + variousFormatPatterns.toString() );

variousFormatPatterns = java.time.format.DateTimeFormatter.ofPattern("yy-MM-dd");
System.out.println("\nTest 2: " + variousFormatPatterns.toString() );

variousFormatPatterns = java.time.format.DateTimeFormatter.ofPattern("yyMMdd");
System.out.println("\nTest 3: " + variousFormatPatterns.toString() );

variousFormatPatterns = java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
System.out.println("\nTest 4: " + variousFormatPatterns.toString() );

Results (note the retention of the space/hyphen/slash/colon delimiter characters):

Test 1: ReducedValue(YearOfEra,2,2,2000-01-01)' 'Value(MonthOfYear,2)' 'Value(DayOfMonth,2)

Test 2: ReducedValue(YearOfEra,2,2,2000-01-01)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)

Test 3: ReducedValue(YearOfEra,2,2,2000-01-01)Value(MonthOfYear,2)Value(DayOfMonth,2)

Test 4: Value(MonthOfYear,2)'/'Value(DayOfMonth,2)'/'Value(YearOfEra,4,19,EXCEEDS_PAD)' 'Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Value(SecondOfMinute,2)

Implementing this approach would require studying the code in java.time.format.DateTimeFormatterBuilder. The JavaDoc for the appendPattern(String pattern) method appears to be particularly useful. You might be able to take some shortcuts if you know you are working with only a few types of patterns.

Taking a quick glance through the DateTimeFormatterBuilder code, there would likely be a risk relying on this type of solution as the Strings such as Value, ReducedValue, Fraction, etc. could change without notice in future Java versions.



来源:https://stackoverflow.com/questions/28949179/get-original-pattern-string-given-a-jdk-8-datetimeformatter

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