I'm using jaspersoft's iReport and I want to turn the new java.util.Date()
(which is the current date) into 1 month prior from that date. What do I write in the text field expression to achieve this?
You can use Joda-Time Java API. Call the minusMonths
method on a DateTime
object.
The jrxml file sample:
<?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="joda_sample" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<import value="org.joda.time.DateTime"/>
<title>
<band height="79" splitType="Stretch">
<textField>
<reportElement x="109" y="23" width="175" height="20"/>
<textElement/>
<textFieldExpression><![CDATA["Current date: " + new SimpleDateFormat("dd.MM.yyyy").format(new Date())]]></textFieldExpression>
</textField>
<textField>
<reportElement x="336" y="23" width="200" height="20"/>
<textElement/>
<textFieldExpression><![CDATA["Current date minus one month: " + DateTime.now().minusMonths(1).toString("dd.MM.yyyy")]]></textFieldExpression>
</textField>
</band>
</title>
</jasperReport>
The result will be:
Note: Don't forget to add Joda-Time library to classpath (in my case I've add library to the iReport's classpath).
The Java Date API is notoriously clumsy, there is a useful third party alternative. Try importing http://joda-time.sourceforge.net/ library.
See this post: Adding a number of days to a JodaTime Instant
You can use the Calendar class, in the following way:
Calendar c=Calendar.getInstance();
c.setTime(myDate); //Yes, it is strange!!! But we don't really need this, for the getInstance() results in a current date.
c.add(Calendar.MONTH, -1);
I realized after your comment that I can't change it into a single expression, for add returns void and not the new Date(). Sorry about that...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With