-3

Given a time in milliseconds, how can you check if it was yesterday?

RaminS
  • 2,208
  • 4
  • 22
  • 30
Dr. Bright
  • 19
  • 7

3 Answers3

2

You would first convert the millis to a Date or LocalDate and then run the comparison.

Here's a quick example:

import java.time.*;


class DateCheckSample {
    public static void main(String[] args) {

        // Our input date
        long millis = System.currentTimeMillis();

        // Convert the millis to a LocalDate
        Instant instant = Instant.ofEpochMilli(millis);
        LocalDate inputDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

        // Grab today's date
        LocalDate todaysDate = LocalDate.now();

        System.out.println(millis);

        // Check if date is yesterday
        if (todaysDate.minusDays(1).equals(inputDate)) {
            System.out.println(inputDate + " was yesterday!");
        } else {
            System.out.println(inputDate + " was NOT yeseterday!");
        }
    }
}

The Result:

2019-02-16 was NOT yesterday!

If you'd like to confirm it's working, just subtract 100000000 from millis before running.

Side Note: As pointed out in the comments on your question, 23:59 is not a millis value...

Zephyr
  • 9,885
  • 4
  • 28
  • 63
0

If you don't want to use Date, you can simply use the modulus operator with a bit of clever arithmetics. System#currentTimeMillis returns the amount of milliseconds that have passed since January 1, 1970, midnight (00:00).

Combining this with the number of milliseconds in a day (86,400,000), we can figure the time at which the last start of day was — which is when today began. Then we can see if the time given to us is smaller or larger than that value.

boolean isToday(long milliseconds) {
    long now = System.currentTimeMillis();
    long todayStart = now - (now % 86400000);
    if(milliseconds >= todayStart) {
        return true;
    }
    return false;
}

To check if a time is yesterday instead of today, we simply check if it is between the start of today and the start of yesterday.

boolean isYesterday(long milliseconds) {
    long now = System.currentTimeMillis();
    long todayStart = now - (now % 86400000);
    long yesterdayStart = todayStart - 86400000;
    if(milliseconds >= yesterdayStart && < todayStart) {
        return true;
    }
    return false;
}
uneq95
  • 2,158
  • 2
  • 17
  • 28
RaminS
  • 2,208
  • 4
  • 22
  • 30
-1

You can convert the milliseconds to Date and then compare the day with today's Date.

For reference: Convert millisecond String to Date in Java

uneq95
  • 2,158
  • 2
  • 17
  • 28