How can i calcutate the second that are between a currentTime and another date?
long time = myData - SystemClock.elapsedRealtime();
How can i calcutate the second that are between a currentTime and another date?
long time = myData - SystemClock.elapsedRealtime();
You use System.currentTimeMillis()
to get current. Then use System.currentTimeMillis()
again on the time of offset. Then use the latest one and subtract the first one.
SystemClock.elapsedRealtime(); returns time since bootup. not a speific time.
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using the modern API:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
// An arbitrary GregorianCalendar for demo - you will get it from object.getData
GregorianCalendar gcal = GregorianCalendar
.from(ZonedDateTime.of(2021, 5, 2, 10, 20, 30, 0, ZoneId.systemDefault()));
ZonedDateTime start = gcal.toZonedDateTime();
ZonedDateTime current = ZonedDateTime.now(ZoneId.systemDefault());
long seconds = ChronoUnit.SECONDS.between(start, current);
System.out.println(seconds);
}
}
Output:
353263
Note: In the code given above, I have used ZoneId.systemDefault()
which returns the ZoneId
of your JVM. Replace it with the applicable ZoneId
e.g. ZoneId.of("Europe/London")
.
Learn more about the 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.
FYI, Joda-Time offers a Seconds
class.
long secs = Seconds.between( new DateTime( myGregCal.getTime() ), DateTime.now() ).getSeconds();