Skip to content
Advertisement

Subtract number of days without impacting the time

I have the following piece of code. I’m trying to get the epoch value t for exactly 10 days ago, at the current time. But when I convert t back to a date/time using https://www.epochconverter.com/, the printed result’s time is not correct. What am I missing?

        long t = LocalDateTime.now()
                .minusDays(10)
                .toEpochSecond(ZoneOffset.UTC) * 1000;


        System.out.println(t);

Advertisement

Answer

I suggest you use OffsetDateTime.now(ZoneOffset.UTC) to get the current Date-Time in UTC and then subtract 10 days from it. Finally, get the epoch seconds from the resulting OffsetDateTime.

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        System.out.println(OffsetDateTime.now(ZoneOffset.UTC).minusDays(10).toEpochSecond());
    }
}

Output:

1631350741

ONLINE DEMO

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.

Advertisement