1

Here is my jsp page source code:

<%@ 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>

Why the output as the following:

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

I expected the "theMonthShiftEndDate" should be 2018-12-31, however, it return 2019-12-31.

According to the Javadoc:

 TemporalAdjusters.lastDayOfMonth() 

Returns the "last day of month" adjuster, which returns a new date set to the last day of the current month.

I run the jsp today, why the problem only occur in the "december" localdate object, not occur in the november?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
HK KNVB
  • 152
  • 1
  • 11
  • If you are sure you always want `2018-12-31` format (ISO 8601 format), you don’t need to specify any formatter. `theMonthShiftStartDate.toString()` will give you what you want (similarly for the other `LocalDate` variables). – Ole V.V. Apr 07 '19 at 07:11

1 Answers1

1

See Wikipedia on week-dates.

Examples:

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


You wrote

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

with the pattern YYYY, you're formatting using week-based-year.
Change your pattern to yyyy-MM-dd, which uses year-of-era

DateTimeFormatter.ofPattern("yyyy-MM-dd"))
LppEdd
  • 20,274
  • 11
  • 84
  • 139