[英]Scala/Java parse date unknown format
I have the following code:我有以下代码:
val dateString = "12/Sep/2017:11:25:29 +0200"
println(LocalDateTime.parse(
dateString,
DateTimeFormatter.ofPattern("dd/LLL/yyyy:HH:mm:ss X")
));
and the following error:和以下错误:
Exception in thread "main" java.time.format.DateTimeParseException:
Text '12/Sep/2017:11:25:29 +0200' could not be parsed at index 3
What is wrong in my format?我的格式有什么问题? I read https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html but do not find the correct one
我读了 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html但没有找到正确的
EDIT1: "dd/MMM/yyyy:HH:mm:ss X" does not work either EDIT1:“dd/MMM/yyyy:HH:mm:ss X”也不起作用
You have to use M
instead of L
( L
is for the numeric format):您必须使用
M
而不是L
( L
用于数字格式):
"dd/MMM/yyyy:HH:mm:ss X"
You probably have also to set the Locale
that java will use to interpret the month (probably your locale is not english)您可能还必须设置
Locale
将用来解释月份的语言环境(可能您的语言环境不是英语)
LocalDateTime.parse("12/Sep/2017:11:25:29 +0200", DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss X", Locale.ENGLISH));
This works for me (with the locale declared, probably also L
will work fine)这对我有用(声明了语言环境,可能
L
也可以正常工作)
The Answer by Sinigaglia is correct but insufficient. Sinigaglia 的答案是正确的,但不充分。 You should specify a
Locale
for which Sep
is recognizable as a month name.您应该指定一个可以将
Sep
识别为月份名称的Locale
。 An English-speaking locale is needed such as Locale.US
.需要一个说英语的语言环境,例如
Locale.US
。
If unspecified the JVM's current default time zone is automatically implicitly applied.如果未指定,则自动隐式应用 JVM 的当前默认时区。
Sep
is not a month name in Russian, French, Japanese, etc. Sep
不是俄语、法语、日语等的月份名称。
Tip: As a general rule, always specify explicitly your intended locale and time zone;提示:作为一般规则,请始终明确指定您的预期语言环境和时区; use the optional arguments.
使用可选的 arguments。 Relying implicitly on the JVM's current defaults can be problematic.
隐式依赖 JVM 的当前默认值可能会有问题。
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MMM/yyyy:HH:mm:ss X" ).withLocale( locale ) ;
String input = "12/Sep/2017:11:25:29 +0200" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;
System.out.println( odt ) ;
See this code run live on IdeOne.com .请参阅此代码在 IdeOne.com 上实时运行。
2017-09-12T11:25:29+02:00
2017-09-12T11:25:29+02:00
As for your use of L
, the Javadoc explains that L
is for the “standalone” month name.至于您对
L
的使用,Javadoc 解释说L
代表“独立”月份名称。 Some languages vary the spelling depending on whether the month is used by itself or in combination.有些语言会根据月份是单独使用还是组合使用来改变拼写。 English is not one of those languages.
英语不是其中一种语言。
Removing /
from the input String should work.从输入字符串中删除
/
应该可以。 (Didn't check) (没查)
val dateString = "12 Sep 2017:11:25:29 +0200"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.