我只是在玩 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"));
还是没用。
编辑: 我还想知道一件事,如果我只希望我的日期对象采用这种格式怎么办?
编辑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/