Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous 30 days starting time in java

Tags:

java

I'm trying to get previous 30 days current date and time.. But, its not something else

new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000)

This is returning

Tue Jul 21 04:41:20 IST 2015

Is there any wrong

like image 316
Syed Avatar asked Dec 15 '22 13:12

Syed


2 Answers

Never, never, ever do anything like System.currentTimeMillis() - 30 * 24 * 60 * 60 * 100, there are so many rules with time manipulation that this kind of thing never works well

Java 8's Time API

LocalDateTime ldt = LocalDateTime.now().minusDays(30);

Which outputs 2015-06-01T16:15:54.868

JodaTime

LocalDateTime ldt = new LocalDateTime();
ldt = ldt.minusDays(30);

Which outputs 2015-06-01T16:18:22.489

Calendar

If you're really desperate

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -30);
Date date = cal.getTime();

Which outputs Mon Jun 01 16:19:45 EST 2015

like image 78
MadProgrammer Avatar answered Dec 17 '22 03:12

MadProgrammer


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

like image 29
arnabkaycee Avatar answered Dec 17 '22 02:12

arnabkaycee