0

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>
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
drt966
  • 5
  • 3
  • 1
    You might be try new Date(System.currentTimeMillis() - (24 * 3600 * 1000)) – halil ibrahim binol Apr 20 '22 at 10:29
  • Yeah it's working with new SimpleDateFormat("dd/MM/yyyy").format(new Date(System.currentTimeMillis() - (24 * 3600 * 1000))) . Thank you a lot – drt966 Apr 20 '22 at 10:32
  • 2
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It also makes subtracting a day easier and easier to get correct (subtracting 24 * 3600 * 1000 milliseconds is not always correct). – Ole V.V. Apr 20 '22 at 11:13

1 Answers1

1

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")
deHaar
  • 17,687
  • 10
  • 38
  • 51