java - 线程中的异常 "main"java.time.format.DateTimeParseException : Text '14/Oct/2016 23:09:25.2110 +0530' could not be parsed at index 0

标签 java datetime

我只是在玩 Java 8 日期时间 API。

我的代码如下所示。

LocalDateTime date=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date);
String ormat = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss"));
//=date.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy'T'hh:mm:ss.SX Z"));
LocalDateTime date2=LocalDateTime.parse(format);

System.out.println("dsate now:"+date2);

但它显示此错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '14/Oct/2016 23:13:57' could not be parsed at index 0

我尝试过这种模式

String format=ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss.SSSS Z"));

还是没用。

我检查了答案herehere .

编辑: 我还想知道一件事,如果我只希望我的日期对象采用这种格式怎么办?

编辑2: 我试图实现的是使用 localDateTime 获得一些日期和时间,并且我想使用我在代码中使用的格式化程序对其进行格式化。

最佳答案

您的 format2 生成字符串 14/Oct/2016 23:26:38

您尝试使用 ISO_LOCAL_DATE_TIME (yyyy-MM-dd'T'hh:mm:ss) 解析该输入字符串。这就是您收到错误的原因。

您必须将日期格式化程序传递给解析方法

LocalDateTime date2=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date2);
String format2=ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss"));
System.out.println(format2);
//=date.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy'T'hh:mm:ss.SX Z"));
LocalDateTime date3=LocalDateTime.parse(format2,
                DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss").withLocale(Locale.ENGLISH));

System.out.println("dsate now:"+date3);

输出:

dsate now:2016-10-14T23:26:38

评论后编辑:

您可以直接格式化LocalDateTime

LocalDateTime date2=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date2);
String myDate1 = date2.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss").withLocale(Locale.ENGLISH));
System.out.println("dsate now:"+myDate1);

关于java - 线程中的异常 "main"java.time.format.DateTimeParseException : Text '14/Oct/2016 23:09:25.2110 +0530' could not be parsed at index 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049193/

相关文章:

java - JPA 中日期到日期时间的转换

c# - 我如何着手将时间变成公共(public)整数?

python datetime.timedelta 放入列表中

java - Oracle 到 Hibernate 到 ISO 8601 日期格式

java - 如何从 Bytebuddy 中的 AnnotationDescription.Loadable 获取注释值

java - Hibernate查询问题

java - 正则表达式的控制台或扫描仪?

Java缓存问题? Eclipse 中的调试器?

python - 带有日期时间和日期的 Django 查询集过滤器

java - 为什么tomcat最新代码在main方法中使用synchronized