当前位置: 首页 > 面试题库 >

如何将LocalDate格式化为yyyyMMDD(不使用JodaTime)

微生俊
2023-03-14
问题内容

我正在尝试获取下一个即将到来的星期五的日期,并将其格式设置为
yyyyMMDD。如果可能,我想不使用JodaTime来执行此操作。这是
我的代码:

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;

// snippet from main method
LocalDate friday = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyyMMDD');
System.out.println(friday.format(formatter));

But when I run this I get the following error (running it today 20170809)

java.time.DateTimeException: Field DayOfYear cannot be printed as the value 223 exceeds the maximum print width of 2

我究竟做错了什么?

编辑:我正在使用Java 8


问题答案:

Big D means day-of-year. You have to use small d.

So in your case use "yyyyMMdd".

You can check all patterns
here.

This particular pattern is built into Java 8 and later:
DateTimeFormatter.BASIC_ISO_DATE



 类似资料:
  • 问题内容: 我有一个名为date的LocalDate变量,当我打印它时显示1988-05-05,我需要将此变量转换为要打印为1988年5月5日。如何执行此操作? 问题答案: 如果他从Java 8中的新功能LocalDate开始,SimpleDateFormat将无法工作。从我所看到的,您将不得不使用DateTimeFormatter,http://docs.oracle.com/javase/8/

  • 我有一个LocalDate变量名为date,当我打印它时,它显示1988-05-05,我需要将它转换成05.may1988。怎么做?

  • 问题内容: Python和Matlab经常具有如下所示的整数日期表示形式: 733828.0 733829.0 733832.0 733833.0 733834.0 733835.0 733836.0 733839.0 733840.0 733841.0 这些数字对应于今年的某些日期。你们知道哪个功能可以将它们转换回YYYYMMDD格式吗? 太感谢了! 问题答案: 该课程可以为您提供帮助。如果将这

  • 我用Java定义了以下格式: 我的应用程序从日历中获取特定日期: 我想以的格式存储另外两个日期。给定的的和。 例如,如果是我想创建以下两个变量- 我该怎么做?

  • 这是GitHub中的项目 在分支master中工作得很好,但问题是,它在名为“localdate”的分支中! 当您单击masterTable fot为JTextFileds lod数据时…

  • 本文向大家介绍如何将Java LocalDateTime格式化为ISO_DATE_TIME格式,包括了如何将Java LocalDateTime格式化为ISO_DATE_TIME格式的使用技巧和注意事项,需要的朋友参考一下 首先,设置日期: 现在,将日期时间格式化为ISO_DATE_TIME格式: 示例 输出结果