Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add seconds to System.currentTimeMills()

Tags:

java

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?

like image 544
Adam Avatar asked Jan 27 '26 00:01

Adam


2 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
like image 85
Spectric Avatar answered Jan 29 '26 13:01

Spectric


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.

  • For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
  • If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

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
like image 27
Arvind Kumar Avinash Avatar answered Jan 29 '26 11:01

Arvind Kumar Avinash