Get epoch time from yesterday in a range of hours

Viewed 748

First off I'm new in this incredible community. This is an amazing site. I'm happy to be part finally.

Every day I have to insert yesterday's data in the DB. For example, today May 22, I have to insert the data of the 21st from 00:00:00 to 23:59:59 in epoch time.

So far I get the epoch time from today with

long now = Instant.now().toEpochMilli();

How could I get yesterday's epoch time? and store the range of hours in two variables? Like

String startDay = 21/05/2020 00:00:00
String endDay = 21/05/2020 23:59:59
2 Answers

You can use java LocalDate like this:

final LocalDate now = LocalDate.now();
final LocalDate yesterday = now.minusDays(1);
final LocalDateTime start = yesterday.atStartOfDay();
final LocalDateTime end = yesterday.atTime(LocalTime.MAX);

And then format date to your desired format.

You can use a ZonedDateTime as an alternative to the answer given by @ArtyomRebrov.

It will take the system time zone implicitly if you don't provide a specific one.

See this example:

public static void main(String[] args) {
    // get a datetime plus time zone information using the system time zone
    ZonedDateTime startToday = ZonedDateTime.now()
                                            // subtract a day
                                            .minusDays(1)
                                            // and take the minimum time a day can have
                                            .with(LocalTime.MIN);
    // use the same datetime to create the end of the day using the maximum time for a day
    ZonedDateTime endToday = startToday.with(LocalTime.MAX);

    // then print the results in date-time format and as epoch millis
    System.out.println("Yesterday's beginning:\t" + startToday + "\t\t\t| " 
                        + startToday.toInstant().toEpochMilli());
    System.out.println("Yesterday's end:\t" + endToday 
                        + "\t| " + endToday.toInstant().toEpochMilli());
}

Which outputs (on my maching in Germany):

Yesterday's beginning:  2020-05-21T00:00+02:00[Europe/Berlin]               | 1590012000000
Yesterday's end:        2020-05-21T23:59:59.999999999+02:00[Europe/Berlin]  | 1590098399999
Related