i am using a reporting tools which only support one line expression
By example I want to get the Date of yesterday
the class Calendar has a add method, but it returns void so
Calendar.getInstance().add(Calendar.DAY_OF_MONTH,-1).getTime()
didn't work
don't know how to get this done
Thanks
Discussion: To get yesterday's date, you need to subtract one day from today's date.
time. LocalDate. Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.
Use Joda-Time:
new org.joda.time.DateTime().minusDays(1).toDate();
If it really has to be a one-liner and it doesn't matter if the code is understandable, I think the following statement should work:
Date yesterday = new SimpleDateFormat("yyyyMMdd").parse(
""+(Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()))-1));
It formats the current date as "yyyyMMdd", e.g. "20100812" for today, parses it as an int: 20100812, subtracts one: 20100811, and then parses the date "20100811" using the previous format. It will also work if today is the first of a month, since the 0th of a month is parsed by a lenient DateFormat as the last day of the previous month.
The format "yyyyDDD" ought to work as well (D being day of year).
For the first day of the current month, you can use a similar trick:
Date firstday = new SimpleDateFormat("yyyyMMdd").parse(
new SimpleDateFormat("yyyyMM").format(new Date())+"01");
Can't you do something like
new Date( new Date().getTime() - 86400000 );
to get the current time, subtract the # of milliseconds in a day, and build a new date object from 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