如何显示上个月相对于日期的最后一天?

How to display last day of previous month relative to a date?

我创建了几个带有时间表达式的变量,以创建基于时间的报告:

// First of month (Returns 01/09/2017)
 new SimpleDateFormat("MM/dd/yyyy").format(java.util.Date.parse("01/" + MONTH(NOW( )) + "/" + YEAR(NOW())))

// First of previous month (Returns 01/08/2017)
 new SimpleDateFormat("MM/dd/yyyy").format(java.util.Date.parse("01/" + (MONTH(NOW( )) - 1) + "/" + YEAR(NOW())))

// Last of month (Returns 30/09/2017)
 new SimpleDateFormat("MM/dd/yyyy").format(java.util.Date.parse(MONTH(NOW( )) + "/" + DAYSINMONTH(NOW())+ "/" + YEAR(NOW())))

我现在正在努力获取上个月的最后一天。我尝试了类似下面的方法,但这当然不能正常工作,因为并非所有月份都有相同的天数。

// Last of previous month (Returns 30/08/2017)
 new SimpleDateFormat("MM/dd/yyyy").format(java.util.Date.parse(
  (MONTH(NOW( )) - 1)
  + "/" +
  DAYSINMONTH(NOW())
  + "/" +
  YEAR(NOW())
 ))

你知道检索上个月最后一天的方法吗?

参考:http://community.jaspersoft.com/questions/843248/last-day-current-month

我可能会解决这个在 java 中创建静态 class 的方法,该方法将日期作为参数,然后使用 Calendar api or similar to return to the desired date, this is how to do it in java

但是,让我们玩得开心,只使用 jasper-reports

因为我们不能使用日历 api(它 returns 无效)我们需要回退 on the org.apache.commons.lang.time.DateUtils as my friend Tunaki 教我。

使用 DateUtils 我们可以先调用 truncate 月份(删除天数)然后我们 addDays -1(-1 天如果我们在月份的第一个日期它将给我们上个月的最后一天)

DateUtils.addDays(DateUtils.truncate(myDate, Calendar.MONTH),-1);

jrxml 示例

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="DateUtil" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="f288086f-db4e-451f-bf32-e1cce6311a27">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <import value="java.util.Calendar"/>
    <import value="org.apache.commons.lang.time.DateUtils"/>
    <parameter name="date" class="java.util.Date">
        <defaultValueExpression><![CDATA[new Date()]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <title>
        <band height="20" splitType="Stretch">
            <textField pattern="MM/dd/yyyy">
                <reportElement x="0" y="0" width="220" height="20" uuid="48878c52-5527-4784-a74a-e2d8df65cc55"/>
                <textFieldExpression><![CDATA[DateUtils.addDays(DateUtils.truncate($P{date}, Calendar.MONTH),-1)]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>

输出(我通过这个答案的那天)

Design note: You should use pattern to format the Date as I do in my example, do not use SimpleDateFormat in expression, using pattern will give you correct object if you export for example to excel.