Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one expression to get the Date of yesterday and the first day of month

Tags:

java

date

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

like image 450
chun Avatar asked Aug 12 '10 12:08

chun


People also ask

How do I find yesterday's date?

Discussion: To get yesterday's date, you need to subtract one day from today's date.

How do I set the previous date in Java?

time. LocalDate. Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.


3 Answers

Use Joda-Time:

new org.joda.time.DateTime().minusDays(1).toDate();
like image 64
Thierry-Dimitri Roy Avatar answered Oct 21 '22 07:10

Thierry-Dimitri Roy


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");
like image 38
jarnbjo Avatar answered Oct 21 '22 08:10

jarnbjo


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?

like image 33
Shawn D. Avatar answered Oct 21 '22 08:10

Shawn D.