We are Borg We are Borg - 11 months ago 81
Java Question

Java, Intellij : Replacing numeric overflow expression with one which doesn't overflow

I have a scheduled job running, where I want to calculate time till last 30 days. For that I am getting a warning that numeric overflow detected in expression. How can I safely give 30 days?

@Scheduled(cron = "0 5 5 * * ?")
public void deleteRepliesAutomatically() {
if(schedulerActive.equals("true")) {
Session session = this.sessionFactory.getCurrentSession();
long now = System.currentTimeMillis();
// Below line gives warning.
long nowMinus1Week = now - (1000 * 60 * 60 * 24 * 30);
Timestamp nowMinus1WeekAsTimeStamp = new Timestamp(nowMinus1Week);
Query query = session.createQuery("from Replies as cm where cm.sortTimeStamp <:limit");
query.setParameter("limit", nowMinus1WeekAsTimeStamp);
List<Replies> repliesList = query.list();
for (Replies replies : repliesList) {

Thank you.

Answer Source

The answer of piet.t is in correct to fix the issue at hand.

But it would be better maintanable to use TimeUnit enum to calculate from one unit to another. For example to have milliseconds of one week:

long millis = TimeUnit.DAYS.toMillis(7);

You can also do a import static for DAYS.