add seconds to System.currentTimeMills()

Viewed 465

I am trying to calculate the time of 100 days from now using the following:

import java.util.Date;
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        System.out.println(new Date(System.currentTimeMillis() + 8640000 * 1000));
    }
}

It gives me back Jan 04 08:57:25 UTC 2021 which is not correct. How should I remedy this?

3 Answers

Use the following:

System.out.println(new Date(System.currentTimeMillis() + (long)8640000 * 1000));

Or

System.out.println(new Date(System.currentTimeMillis() + 8640000L * 1000));

8640000 * 1000 is 8,640,000,000, which exceeds Integer.MAX_VALUE of 2,147,483,647. You can solve this issue by casting it to a long.

This gives the result:

Tue Apr 13 15:26:10 EDT 2021

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Using the modern API:

import java.time.LocalDate;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        LocalDate after100Days = today.plusDays(100);
        System.out.println(after100Days);
    }
}

Output:

2021-04-13

Learn about the modern date-time API from Trail: Date Time.

Using the legacy API:

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) {
        // Change the TimeZone as per your requirement e.g. TimeZone.getTimeZone("Europe/London")
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.add(Calendar.DAY_OF_YEAR, 100);
        Date after100Days = calendar.getTime();
        System.out.println(after100Days);
    }
}

Output:

Tue Apr 13 19:40:11 BST 2021

Try sometime like

LocalDateTime.now().plusDays(100).toString()

or

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); // you could used any format
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 100); // Adding 100 days
String output = sdf.format(c.getTime());
System.out.println(output);
Related