java - 关于 TemporalAdjusters.lastDayOfMonth() 的用法

标签 java localdate java-time dayofmonth

这是我的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,为什么问题只出现在“12月”的localdate对象上,而不出现在11月份?

最佳答案

参见维基百科 week-dates .

Examples:

Monday 29 December 2008 is written "2009-W01-1"
Sunday 3 January 2010 is written "2009-W53-7"

<小时/>

你写的

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

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

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

关于java - 关于 TemporalAdjusters.lastDayOfMonth() 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472299/

相关文章:

java - AmazonS3Client 无法连接

Java:如何从另一个字符串中删除存储为字符串的一组字母的所有出现?

java - Apache POI 无法从 Excel 单元格中正确读取秒数

java - 时区指示符 - "T"和 "Z"在 ISO8601 格式中是否区分大小写?

java - 计算两个 OffsetDateTimes 之间的月数

Java Instant 舍入到下一秒

java - Dart future 值请求不兼容

java - Java的NetBeans代码完成速度非常慢

java - LocalDate:缺少方法 isEqualOrBefore 和 isEqualOrAfter

scala - 如何在 java.time.LocalDate 上隐式排序