Timestamp1 is next day of timestamp2

AsfK :

I have two timestamps and I want to check if the first timestamp is the next day (tomorrow) of the second timestamp.

** Next day not mean 24 hours, just next DAY_OF_MONTH. for example: timestamp of tomorrow 1 a.m. is the next day of today 10 p.m. (although it's only 3 hours) - therefore ts1 - ts2 < 86400 will not help here.

Firstly I think to extract the day of mounth and compare the delta but it's not good becuase the next day can be new month (or new year..)

The only solution I can think is:

Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(1582783200000L);

Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(1582727735000L);

cal2.add(Calendar.DAY_OF_YEAR, 1);
cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);

But it's looks for me very ugly code... Do you know another way to do it?

edwgiz :

It could be slightly simplified with new date-time api

        ZoneId zone = ZoneId.systemDefault();
        boolean nextDay = 1 == ChronoUnit.DAYS.between(
                Instant.ofEpochMilli(1582727735000L).atZone(zone).truncatedTo(ChronoUnit.DAYS),
                Instant.ofEpochMilli(1582783200000L).atZone(zone).truncatedTo(ChronoUnit.DAYS));


Please note the result depends from a time zone. Thus the example refers to the system default, for the production code the explicit time zone should be applied.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12163&siteId=1