Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date problems, finding the date X days ago

Tags:

java

date

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
like image 363
Jesper Avatar asked Jun 22 '11 12:06

Jesper


People also ask

How do you check if a date is after another date in Java?

The java. util. Date. after() method is used to check whether the current instance of the date is after the specified date.

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.

What does date () getTime () do in Java?

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.


2 Answers

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;
like image 137
Konrad Garus Avatar answered Oct 04 '22 18:10

Konrad Garus


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 ) ) );
like image 24
Kris Avatar answered Oct 04 '22 16:10

Kris