我需要輸出格式爲week-based-year
- week-of-week-based-year
的當前日期,即使用ISO week date,其中星期始終始於星期一和星期的第一週今年1月份是第一次至少有四天的時間(所以在一月份的第一個星期四的一週)。使用DateTimeFormatter解析Java時間的星期幾周模式
自2015年12月31日起,週五,週五至週日,即2016年1月1日至3日,全部屬於2015年第53周(「漫長的一年」),2016年第一週開始於週一1月4日。
從DateTimeFormatter spec,我本來期望,我可以只使用模式YYYY-ww
做到這一點(Y
是week-based-year
和w
是week-of-week-based-year
)。
然而,當我嘗試像下面簡單的測試案例:
String dateString = "2016-01-03";
LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String expectedOutput = "2015-53";
String actualOutput = date.format(DateTimeFormatter.ofPattern("YYYY-ww"));
System.out.println("Parsing " + dateString + ", expected "
+ expectedOutput + " but got " + actualOutput);
System.out.println(dateString + " as ISO week date: "
+ date.format(DateTimeFormatter.ISO_WEEK_DATE));
我得到這個:
Parsing 2016-01-03, expected 2015-53 but got 2016-02
2016-01-03 as ISO week date: 2015-W53-7
因此,使用內置-in ISO_WEEK_DATE
formatter做我的預期,但使用YYYY-ww
模式似乎給了我日曆年和周。
我是否誤解了關於ISO日期日期的事情,或者在我的代碼中是否有錯誤,或者...我敢說這是...這是java.time
庫中的錯誤(如this question的情況)?
我知道我可以使用像下面這樣的自定義格式化工具來解決此問題,但在我的情況下,我真的需要使用這種模式。
new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral("-")
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
.toFormatter();
好的,有趣的 - 'DateTimeFormatter'規範沒有提到進場的區域設置。那麼,爲了獲得我以後的ISO-8601「週週年」,我該怎麼做?如果我通過'DateTimeFormatter.ofPattern(「YYYY-ww」)。withLocale(Locale.getDefault())')設置我自己的語言環境(「en-AU」,使用這種ISO格式,我仍然會得到相同的結果。 –
其實,我只是試過locale'德國'和'法國',在這兩種情況下我都會得到預期的'2015-53'。我很確定,星期日而不是星期一作爲一週的第一天(這可以解釋爲什麼它認爲1月3日是第2周)只是美國的事情。但是,謝謝,我可以與它合作! –