Java Date problems, finding the date X days ago

Viewed 7992
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
5 Answers

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 ) ) );
Related