Only one expression to get the Date of yesterday and the first day of month
Solution 1:
Use Joda-Time:
new org.joda.time.DateTime().minusDays(1).toDate();
Solution 2:
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");
Solution 3:
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?
Solution 4:
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();