i have an epoch timestamp of 1567318967 (September 1, 2019 6:22:47 AM). From the given epoch timestamp, How do I get the previous hour and previous day and output the result in epoch using Java?
I.e.
previous hour: output result: 1567315367 (September 1, 2019 5:22:47 AM)
previous day: output result: 1567232567 (August 31, 2019 6:22:47 AM)
Given timestamp of 1567318967 , i have attempt the following
previousDayInEpoch = moment(timestamp).substract(1, days)
previosHourInEpoch = moment(timestamp).substract(1, hour)
Would like to use Java to output the previous Day and previous Hour result.
This is one of the cases where java.time, the modern Java date and time API, excels:
ZoneId zone = ZoneId.of("Pacific/Kwajalein");
long originalTimestamp = 1_567_318_967L;
ZonedDateTime dateTime = Instant.ofEpochSecond(originalTimestamp).atZone(zone);
long anHourLess = dateTime.minusHours(1).toInstant().getEpochSecond();
System.out.println("previous hour: " + anHourLess);
long aDayLess = dateTime.minusDays(1).toInstant().getEpochSecond();
System.out.println("previous day: " + aDayLess);
Output is what you expected:
previous hour: 1567315367 previous day: 1567232567
The important thing to notice when subtracting a day is that a day is not always 24 hours. It may sometimes be for example 23 hours, 23.5 hours or 25 hours, for example when going into summer time (DST) and back. ZonedDateTime
knows the length of this particular day in the time zone specified, so is the class that we need to use. It is therefore also important that you fill in your desired time zone where I put Pacific/Kwajalein.
Edit: To use the system time zone:
ZoneId zone = ZoneId.systemDefault();
This uses the default time zone setting of the JVM, which usually is picked up from the OS when the JVM is launched. The setting may however be changed at any time by any program running in the same JVM, so is generally fragile. Use at your own risk (or your user’s own risk).
Also curious about using the Instant, would you please update the answer for the other option which is considering 24 hours ago.
In this case we don’t need any time zone nor any ZonedDateTime
. To subtract an hour or a day (always 24 hours) from an Instant
, you need to know how. It goes like this:
Instant originalInstant = Instant.ofEpochSecond(originalTimestamp);
long anHourLess = originalInstant.minus(1, ChronoUnit.HOURS).getEpochSecond();
System.out.println("previous hour: " + anHourLess);
long aDayLess = originalInstant.minus(1, ChronoUnit.DAYS).getEpochSecond();
System.out.println("previous day: " + aDayLess);
In this case the output is identical to the one above.
Oracle tutorial: Date Time explaining how to use java.time.