Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking "new java.util.Date()" and making it 1 month prior

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?

like image 867
precose Avatar asked Jun 05 '12 18:06

precose


3 Answers

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:

The result in iReport

Note: Don't forget to add Joda-Time library to classpath (in my case I've add library to the iReport's classpath).

like image 157
Alex K Avatar answered Sep 16 '22 13:09

Alex K


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

like image 44
Clinton Bosch Avatar answered Sep 16 '22 13:09

Clinton Bosch


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...

like image 37
rlinden Avatar answered Sep 16 '22 13:09

rlinden