我用时间表达式创建了几个变量,以创建基于时间的报告:
// 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
答案 0 :(得分:0)
我可能已经解决了这个在java中创建静态类的方法,该方法将日期作为参数,然后使用Calendar
api或类似的方法返回到所需的日期,这是如何在java Calendar - Get last day of previous month中完成。
但是,让我们玩得开心,只使用jasper-reports
由于我们无法使用日历api(它返回无效),我们需要在again上退回org.apache.commons.lang.time.DateUtils
,因为我的朋友Tunaki教我。
使用DateUtils
我们可以先调用truncate
一个月(删除天数),然后我们调用addDays
-1(如果我们是在第一个月的第一天,它会给我们上个月的最后一天)
DateUtils.addDays(DateUtils.truncate(myDate, Calendar.MONTH),-1);
<?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>
设计说明:您应该像我在示例中一样使用模式格式化日期,不要在表达式中使用
SimpleDateFormat
,如果导出为使用模式将为您提供正确的对象excel的例子。