So LocalDateTime
is a representation of time in your current timezone, you then get the seconds from epoch in the UTC time zone. But what this doesn't do, is convert the time to UTC, it stays unchanged, so if it's 6pm local time, this will generate a time of 6pm UTC.
What you need to do is take into account the timezone. Each of the following statements will print the same value (in seconds) and when I plug them into https://www.epochconverter.com, they give the correct "local time" for when they were generated.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) {
TimeZone tz = TimeZone.getDefault();
ZoneOffset offset = tz.toZoneId().getRules().getStandardOffset(Instant.now());
long t = LocalDateTime.now()
.minusDays(10)
.toEpochSecond(offset);
System.out.println(t);
System.out.println(ZonedDateTime.now().minusDays(10).toEpochSecond());
System.out.println(OffsetDateTime.now(ZoneOffset.UTC).minusDays(10).toEpochSecond());
}
}
There's probably a few more ways to do this, but these were my basic approaches.
So, for example, I got an output of 1631350948
and when I plugged it into the convert, it printed
GMT: Saturday, 11 September 2021 9:02:28 AM
Your time zone: Saturday,
11 September 2021 7:02:28 PM GMT+10:00
Relative: 10 days ago
The "local time" is correct for when I sampled the output