Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Date: seven days ago

I have a report created in Jasper Reports which ONLY recognizes java.util.Date's (not Calendar or Gregorian, etc).

Is there a way to create a date 7 days prior to the current date?

Ideally, it would look something like this:

new Date(New Date() - 7) 

UPDATE: I can't emphasize this enough: JasperReports DOES NOT RECOGNIZE Java Calendar objects.

like image 479
Ramy Avatar asked Feb 04 '11 20:02

Ramy


People also ask

How to get 7 days back Date in java?

Use the Calendar-API: // get Calendar instance Calendar cal = Calendar. getInstance(); cal. setTime(new Date()); // substract 7 days // If we give 7 there it will give 8 days back cal.

How do I subtract days from a date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.

How do I set the past date in Java?

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


2 Answers

From exactly now:

long DAY_IN_MS = 1000 * 60 * 60 * 24; new Date(System.currentTimeMillis() - (7 * DAY_IN_MS)) 

From arbitrary Date date:

new Date(date.getTime() - (7 * DAY_IN_MS)) 

Edit: As pointed out in the other answers, does not account for daylight savings time, if that's a factor.

Just to clarify that limitation I was talking about:

For people affected by daylight savings time, if by 7 days earlier, you mean that if right now is 12pm noon on 14 Mar 2010, you want the calculation of 7 days earlier to result in 12pm on 7 Mar 2010, then be careful.

This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.

However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS may return a result in(7 Mar 2010 12:00pm) where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm vs 12pm). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.

If DST isn't a factor for you or if you really do want (168 hours) exactly (regardless of the shift in wall-clock time), then this solution works fine.

Otherwise, you may need to compensate for when your 7 days earlier doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).

like image 124
Bert F Avatar answered Sep 22 '22 06:09

Bert F


Use Calendar's facility to create new Date objects using getTime():

import java.util.GregorianCalendar; import java.util.Date;  Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, -7); Date sevenDaysAgo = cal.getTime(); 
like image 22
Powerlord Avatar answered Sep 21 '22 06:09

Powerlord