Do not perform the calculation yourself if there is a standard API available to do the same.
import java.time.Instant;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
long seconds = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
System.out.println(seconds);
// Alternatively, using java.time API
seconds = Instant.now().getEpochSecond();
System.out.println(seconds);
}
}
ONLINE DEMO
Coming back to your problem:
You can use DocumentSnapshot#getTimestamp
to get the Timestamp
from which you can get the seconds using Timestamp#getSeconds
.
Thus, you can do it like
long diff = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - document.getTimestamp("createdAt").getSeconds();
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*.
Solution using java.time
, the modern Date-Time API:
Using Timestamp#todate
, you can convert Timestamp
to java.util.Date
which can be converted into java.time.Instant
and then you can use java.time.Duration
to find the difference in seconds as shown below:
long seconds = Duration.between(Instant.now(), document.getTimestamp("createdAt").toDate().toInstant()).toSeconds();
Learn more about 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.