Get previous 30 days starting in java
Never, never, never do anything like this System.currentTimeMillis() - 30 * 24 * 60 * 60 * 100
, there are so many time manipulation rules that this property never works well.
Java 8 Time API
LocalDateTime ldt = LocalDateTime.now().minusDays(30);
What are the outputs 2015-06-01T16:15:54.868
JodaTime
LocalDateTime ldt = new LocalDateTime(); ldt = ldt.minusDays(30);
What are the outputs 2015-06-01T16:18:22.489
The calendar
If you are really desperate
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -30);
Date date = cal.getTime();
What are the outputs Mon Jun 01 16:19:45 EST 2015
source to share
You can use Apache Commons library (commons-lang) .
Date currentDate = new Date();
Date dateBefore30Days = DateUtils.addDays(currentDate, -30);
See this link for more details: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html
source to share
The code you provided new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000)
may give incorrect results as it does not consider any date / time logic implemented by Java. This will only give a mathematically correct result, not a logically correct result.
You can use the class java.util.Calendar
without using an external library.
Calendar calendar = Calendar.getInstance(); // get Calendar Instance
calendar.add(Calendar.DATE, -30); // add -30 days as you need to subtract 30 days
Date dateRequired = calendar.getTime(); // get the new date from modified cal object.
source to share