4

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
Rusty23
  • 71
  • 2
  • 8

2 Answers2

6

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.

Artyom Rebrov
  • 651
  • 6
  • 23
  • Thanks for the answer. LocalDate and LocalDateTime are in epoch time format? – Rusty23 May 22 '20 at 08:12
  • 1
    To get the LocalDateTime in milliseconds you can do it as seen [in this answer](https://stackoverflow.com/a/23945792/896249) `start.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();` to get the "start" time in epoch milliseconds – GameDroids May 22 '20 at 08:13
  • FYI: the `ZoneId.systemDefault()` is the tricky part: it depends on your machine where you execute the code. – GameDroids May 22 '20 at 08:15
  • wow, thank you very much. I'll try in an hour. I'll let you know if it works – Rusty23 May 22 '20 at 08:15
4

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
deHaar
  • 17,687
  • 10
  • 38
  • 51