java 如何将 LocalDate 格式化为 yyyyMMDD(没有 JodaTime)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45598094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format LocalDate to yyyyMMDD (without JodaTime)
提问by zero01alpha
I am trying to get the date of the the next upcoming Friday and format it as yyyyMMDD. I would like to do this without using JodaTime if possible. Here is my code:
我正在尝试获取下一个即将到来的星期五的日期并将其格式化为 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)
但是当我运行它时,我收到以下错误(今天运行它 20170809)
java.time.DateTimeException: Field DayOfYear cannot be printed as the value 223 exceeds the maximum print width of 2
What am I doing wrong?
我究竟做错了什么?
edit: I am using Java 8
编辑:我正在使用 Java 8
回答by ByeBye
Big Dmeans day-of-year. You have to use small d.
大的D意思day-of-year。你必须使用小d.
So in your case use "yyyyMMdd".
所以在你的情况下使用"yyyyMMdd".
You can check all patterns here.
您可以在此处查看所有模式。
This particular pattern is built into Java 8 and later: DateTimeFormatter.BASIC_ISO_DATE
此特定模式内置于 Java 8 及更高版本中: DateTimeFormatter.BASIC_ISO_DATE
回答by Todd
I think you have two problems.
我认为你有两个问题。
First, you are enclosing a String in character literals (''vs "").
首先,您将字符串包含在字符文字 ( ''vs "") 中。
Second, the DD(day of year) in your format string needs to be dd(day of month).
其次,DD格式字符串中的(day of year) 必须是dd(day of month)。
DateTimeFormatter.ofPattern("yyyyMMdd");

