关于TemporalAdjusters.lastDayOfMonth()[duplicate]的用法

问题描述 投票:1回答:1

这是我的jsp页面源代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.time.format.DateTimeFormatter"%>  
<%@ page import="java.time.temporal.TemporalAdjusters"%>  
<%@ page import="java.time.LocalDate"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Local Date Demo</title>
</head>
<body>
<%
int year=2018,month=12,date=1;
LocalDate theMonthShiftStartDate=LocalDate.of(year,month,date);
LocalDate theMonthShiftEndDate=theMonthShiftStartDate.with(TemporalAdjusters.lastDayOfMonth());  
LocalDate previousMonthShiftStartDate=theMonthShiftStartDate.plusMonths(-1);
LocalDate previousMonthShiftEndDate=previousMonthShiftStartDate.with(TemporalAdjusters.lastDayOfMonth());

%>
theMonthShiftStartDate=<%=theMonthShiftStartDate.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))%><br>
theMonthShiftEndDate=<%=theMonthShiftEndDate.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))%><br>
previousMonthShiftStartDate=<%=previousMonthShiftStartDate.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))%><br>
previousMonthShiftEndDate=<%=previousMonthShiftEndDate.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))%><br>

</body>
</html>

为什么输出如下:

 theMonthShiftStartDate=2018-12-01
 theMonthShiftEndDate=2019-12-31
 previousMonthShiftStartDate=2018-11-01
 previousMonthShiftEndDate=2018-11-30

我预计“theMonthShiftEndDate”应该是2018-12-31,然而,它返回2019-12-31。

根据Javadoc:

 TemporalAdjusters.lastDayOfMonth() 

返回“最后一天”调整器,它返回设置为当前月份最后一天的新日期。

我今天运行jsp,为什么问题只发生在“十二月”localdate对象中,而不是发生在十一月?

java localdate java.time dayofmonth
1个回答
1
投票

请参阅week-dates上的维基百科。

例子:

2008年12月29日星期一写成“2009-W01-1” 2010年1月3日星期日写成“2009-W53-7”


你写了

DateTimeFormatter.ofPattern("YYYY-MM-dd"))

使用模式YYYY,您使用基于周的年份进行格式化。 将您的模式更改为使用年代的yyyy-MM-dd

DateTimeFormatter.ofPattern("yyyy-MM-dd"))
© www.soinside.com 2019 - 2024. All rights reserved.