tags:

views:

63

answers:

4

Hi 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

+1  A: 

Use Joda-Time:

new org.joda.time.DateTime().minusDays(1).toDate();
Thierry-Dimitri Roy
Sure, joda time again, but if he's restricted to one-liners, then I actually doubt that he can include 3rd-party libs.
Andreas_D
+2  A: 

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?

Shawn D.
Should work with `System.currentTimeMillis()` instead of `new Date().getTime()` too.
Andreas_D
Good point. Better to reduce the # of objects.
Shawn D.
The logic is wrong, since not all days have 86400000ms.
jarnbjo
I guess this really just highlights the problems with Java's date libraries... at least for me, it shouldnt be more than a one liner to create a date object of yesterday, and shouldn't require Joda...
Stephen
@Shawn D. will be a pb when when we change to Daylight Saving Time
chun
+1  A: 

Assuming you want a java.util.Date object (since you used getTime() in your question and that returns a java.util.Date), you could do:

// Get yesterday's date. System.currentTimeMillis() returns the
// number of milliseconds between the epoch and today, and the
// 86400000 is the number of milliseconds in a day.
new Date(System.currentTimeMillis() - 86400000);

Oops, didn't see your first day of the month query before. I came up with the following to get that using util.Date, but I think this is about the time you want to switch to using Joda or Calendar... (dear SO, please don't vote me down for the horrendousness of the following...)

// This will return the day of the week as an integer, 0 to 6.
new Date(System.currentTimeMillis() - ((new Date().getDate()-1) * 86400000)).getDay();
Stephen
+1  A: 

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");
jarnbjo
@jarnbjo thanks~~ works well
chun