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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With