我刚刚玩Java 8 Date time 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获得的日期和时间,我想使用我在代码中使用的格式化程序来格式化它。
答案 0 :(得分:1)
您的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);