0

I understand that you can get the Unix Epoch in milliseconds in an android application using the following code:

System.currentTimeMillis()

How would you therefore get the value 30 minutes before?

Apqu
  • 4,880
  • 8
  • 42
  • 68

2 Answers2

4

Consider using mathematics. There are 1000 milliseconds in a second, 60 seconds in a minute. Therefore:

System.currentTimeMillis() - 30 * 60 * 1000
laalto
  • 150,114
  • 66
  • 286
  • 303
2

java.time

With java.time, the modern date-time API, you can do it without performing any calculations yourself.

Demo:

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        long millisNow = System.currentTimeMillis();
        Instant instantNow = Instant.ofEpochMilli(millisNow);
        Instant instant30MinsAgo = instantNow.minus(30, ChronoUnit.MINUTES);
        long millis30MinsAgo = instant30MinsAgo.toEpochMilli();
        // System.out.println(millis30MinsAgo);

        // In a single command
        long millisThrityMinsAgo = Instant.ofEpochMilli(System.currentTimeMillis())
                                    .minus(30, ChronoUnit.MINUTES)
                                    .toEpochMilli();
        
        // System.out.println(millisThrityMinsAgo);
    }
}

With the following code, you can get the current instant without using System.currentTimeMillis():

Instant.now()

Thus, you can get the Unix Epoch milliseconds 30 minutes ago with the following code also:

Instant.now().minus(30, ChronoUnit.MINUTES).toEpochMilli()

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110