[英]How to compare two dates created as JodaTime LocalDate and LocalDateTime?
[英]How to format LocalDate to yyyyMMDD (without JodaTime)
我正在嘗試獲取下一個即將到來的星期五的日期,並將其格式化為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));
但是當我運行這個時,我得到以下錯誤(今天運行它20170809)
java.time.DateTimeException: Field DayOfYear cannot be printed as the value 223 exceeds the maximum print width of 2
我究竟做錯了什么?
編輯:我使用的是Java 8
Big D
表示day-of-year
。 你必須使用小d
。
所以在你的情況下使用"yyyyMMdd"
。
你可以在這里查看所有模式。
此特定模式內置於Java 8及更高版本: DateTimeFormatter.BASIC_ISO_DATE
我認為你有兩個問題。
首先,您在字符文字中包含一個字符串( ''
vs ""
)。
其次,格式字符串中的DD
(一年中的某一天)需要為dd
(月中的某天)。
DateTimeFormatter.ofPattern("yyyyMMdd");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.