Date nowdate = new Date();
long nowms = nowdate.getTime();
long differencems = numdaysback * 24 * 60 * 60 * 1000;
long thenms = nowms - differencems;
Date thendate = new Date(thenms);
If numdaysback is 365, then I would suppose that thendate would be one year ago. but it's not... it's about three weeks ago?!?
NUMDAYSBACK: 365
NOWDATE: Wed Jun 22 20:31:58 SGT 2011
NOWMS: 1308745918625
DIFFERENCEMS: 1471228928
THENMS: 1307274689697
THENDATE: Sun Jun 05 19:51:29 SGT 2011
The java. util. Date. after() method is used to check whether the current instance of the date is after the specified date.
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.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
How about:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
Date thendate = cal.getTime();
Returns the same time of day regardless of DST or leap years, is shorter and clearer...
Generally Calendar
is the way to go in such cases (unless you use a 3rd party library like Joda Time). You can use it for all kinds of calculations: add N days/hours/months/seconds, truncate time to a whole hour etc. - stuff that would be too much pain with long
only.
Regarding your original question, it seems to be a victim of integer overflow. It works if the multiplication explicitly uses long:
long differencems = 365 * 24 * 60 * 60 * 1000L;
If you are using Java 8 and up, you can use the newer java.time library to do this a bit more cleanly.
Date xDaysAgo = Date.from( Instant.now().minus( Duration.ofDays( x ) ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With