Do not do your own time calculations. Working with a date is an amazingly complex business. You have already encountered a common error int -versus- long with the calculation of milliseconds. Use a decent time library. Fortunately, Java now comes with the industry's best library.
java.time
As rgettman's correct answer already mentioned, you should use the new java.time framework built into Java 8 and later. Older date and time classes associated with the earliest versions of Java are notoriously unpleasant.
The basics of java.time ... Instant is the moment on the timeline in UTC. Apply the time zone ( ZoneId ) to get the ZonedDateTime .
The time zone is critical for determining dates, since the date is not the same worldwide at any time. A new day is coming in the east.
Instant instant = Instant.now(); // In UTC. ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ); ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); ZonedDateTime zdtTwentyFiveDaysAgo = zdt.minusDays( 25 );
You may need the first moment of the day for this date 25 days ago, and not at the current time of the day. The first point is not always 00:00:00.0 due to daylight saving time (DST) and possibly other anomalies. Therefore, let java.time determine the time of day. We have to go through LocalDate and then go back to ZonedDateTime to get the first moment.
ZonedDateTime zdtTwentyFiveDaysAgoStart = zdtTwentyFiveDaysAgo.toLocalDate().atStartOfDay( zoneId );
source share