如何呈现可以通过Java中的任何DateTimeFormatter模式解析的日期? [英] How to present a date that can be parsed by any DateTimeFormatter pattern in Java?
问题描述
String date =....
DateTimeFormatter format = DateTimeFormat.forPattern (我想要的任何模式);
DateTime result = format.parseDateTime(date);
还是日期必须遵循模式?感谢您的帮助
不,你不能得到一个适合所有的尺寸。想想你的字符串是不是一个合法的日期,像你好,你怎么解析?
java.time
Java 8及更高版本包括 java.time 框架(教程) 。 java.time 格式化程序的模式可能会包含 []
来标记可选部分。这给你一些灵活性。说你使用格式:
M [M] ['/'] [' - '] ['。'] d [d] ['/'] [' - '] ['。'] yyyy [''] ['T'] [''] h [h]:mm:ss
所以在这种情况下,您的字符串可能有一个或两个数字,指定月,日,小时。月份,日期和年份可以由分隔。
, -
或 /
等等。例如,使用以上格式,以下字符串将被成功解析: 1/10/1995 9 :34:45
01-10-1995 09:34:45
01.10.1995T09:34:45
...等等。
我写了一个具有一组模式的实用程序。一旦获得了一个String,它会尝试用集合中的所有模式来解析它,并且看到它们是否与其中一个成功。如果您正确地编写了一组模式,您可以确保您的util支持任何可能的字符串,表示有效的日期。
I'm working with a software that uses a lot of DateTimeFormat parsing, in order to minimize the errors, I wonder if I can present the date String in a certain way that it can be parsed by any DateTimeFormat pattern. Ideally it should work as follows:
String date = "...."
DateTimeFormatter format = DateTimeFormat.forPattern(any pattern I want);
DateTime result = format.parseDateTime(date);
Or does the date have to follow the pattern? Thanks for your help
解决方案 No, you can not get one size fits all. Think if your string is not a legal date at all, something like "hello", how are you going to parse it?
java.time
Java 8 and later includes the java.time framework (Tutorial). The java.time formatter’s pattern may contain []
to mark optional parts. This gives you some flexibility. Say you use format:
M[M]['/']['-']['.']d[d]['/']['-']['.']yyyy[' ']['T'][' ']h[h]:mm:ss
So in this case your string may have one or two digits specifying month, day and hour. Month, day and year may be separated by .
, -
or /
and so forth. For example with format above the following strings will be parsed successfully:
1/10/1995 9:34:45
01-10-1995 09:34:45
01.10.1995T09:34:45
…and so forth.
I wrote a utility that has a set of patterns. Once it gets a String it tries to parse it with all the patterns in the set and sees if it succeeds with one of them. If you write such a set of patterns correctly you may ensure that your util supports any possible String that denotes a valid date.
这篇关于如何呈现可以通过Java中的任何DateTimeFormatter模式解析的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!