Search code examples
javadatejasper-reportsdaysdate-manipulation

Substract one day of date in Jasper


i have this code in my JasperReport like that new SimpleDateFormat("dd/MM/yyyy").format(new Date()) - 24 * 3600 * 1000 but it's not working, what i'm trying is substract one day from today. But it's displaying the day of today like that

<textFieldExpression><![CDATA["Test: " + new SimpleDateFormat("dd/MM/yyyy").format(new Date()) - 24 * 3600 * 1000]]></textFieldExpression>

Solution

  • As far as I can see, this code obviously ignores the - 24 * 3600 * 1000 because the expression new SimpleDateFormat("dd/MM/yyyy").format(new Date()) determines the value before you try to subtract one day ignoring the arithmetic that follows. It only considers the new Date(), which is today.

    You should include the calculation before formatting, e.g.

    new SimpleDateFormat("dd/MM/yyyy").format(new Date(System.currentTimeMillis() - (24 * 3600 * 1000)))
    

    If you are on Java 8 or higher, I would use java.time, maybe like this:

    LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("dd/MM/uuuu")