Add milliseconds to Java date, when milliseconds is long

Viewed 82942

I am looking for the best way to add milliseconds to a Java Date when milliseconds is stored as a 'long'. Java calendar has an add function, but it only takes an 'int' as the amount.

This is one solution I am proposing...

Calendar now = Calendar.getInstance();
Calendar timeout = Calendar.getInstance();

timeout.setTime(token.getCreatedOn());
timeout.setTimeInMillis(timeout.getTimeInMillis() + token.getExpiresIn());

Any other suggestions?

4 Answers

java.time

The java.util Date-Time API 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*.

Demo using java.time, the modern API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant createdOn = Instant.ofEpochMilli(1_622_800_000_000L);
        System.out.println(createdOn);

        Instant timeout = createdOn.plusMillis(50_000L);
        System.out.println(timeout);
    }
}

See this code run live at IdeOne.com.

Output:

2021-06-04T09:46:40Z
2021-06-04T09:47:30Z

An Instant represents an instantaneous point on the timeline in UTC. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

So, the solution to your problem would be:

Instant createdOn = token.getCreatedOn().toInstant();
Instant timeout = createdOn.plusMillis(token.getExpiresIn());

Check documentation of Date#toInstant to learn more about it.

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.


* 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.

Related