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

I use reporting tools that support only one row expression

As an example, I want to get the date of yesterday

the Calendar class has an add method, but it returns void, so

Calendar.getInstance().add(Calendar.DAY_OF_MONTH,-1).getTime()

does not work

don't know how to do it

thank

+5
source share
6 answers

If it really should be single-line, and it doesn't matter if the code is clear, I think the following instruction should work:

Date yesterday = new SimpleDateFormat("yyyyMMdd").parse(
    ""+(Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()))-1));

"yyyyMMdd", . "20100812" int: 20100812, : 20100811, "20100811" . , , 0- ​​ DateFormat .

"yyyyDDD" (D - ).

:

Date firstday = new SimpleDateFormat("yyyyMMdd").parse(
    new SimpleDateFormat("yyyyMM").format(new Date())+"01");
+2

Joda-Time:

new org.joda.time.DateTime().minusDays(1).toDate();
+4

-

new Date( new Date().getTime() - 86400000 );

, ?

+2

, java.util.Date ( getTime() java.util.Date), :

// Get yesterday 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);

, . , util.Date, , , Joda Calendar... (, , ...)

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

:

Calendar cal = Calendar.getInstance();
cal .add(Calendar.DAY_OF_MONTH,-1);
cal .getTime();

:

Calendar.getInstance().add(Calendar.DAY_OF_MONTH,-1).getTime()

(add()), void .getTime(). .

0

, JasperReports:

// Today
new java.util.Date().format('yyyy-MM-dd')
// Yesterday
new SimpleDateFormat("yyyy-MM-dd").format(new Date()-1)

// First Day of current month
new java.util.Date().format('yyyy') + "-" + new java.util.Date().format('MM') + "-01"

ISO YYYY-MM-DD, (dd/mm ).

0
source

All Articles