Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Median Date between two dates using Java 8

Tags:

java

java-time

I'm finding it difficult that what it sounds.

So, I have a max date and a min date and I need to find the median date between these two dates. I use Java 8 to find my max and min dates,

LocalDate gerbutsmin = YearMonth.now().plusMonths(2).atDay(1);
LocalDate gerbutsmax = YearMonth.now().plusMonths(15).atDay(1);

How would I go ahead after this? Maybe I need to switch back to Calander?

like image 466
whydoieven Avatar asked Sep 08 '25 01:09

whydoieven


1 Answers

Try using DAYS.between():

LocalDate gerbutsmin = YearMonth.now().plusMonths(2).atDay(1);
LocalDate gerbutsmax = YearMonth.now().plusMonths(15).atDay(1);
long numDays = ChronoUnit.DAYS.between(gerbutsmin, gerbutsmax);
LocalDate median = gerbutsmin.plusDays(numDays / 2L);  // plusDays takes a long
System.out.println(median);

2019-03-17
(output as of today, which is 2019-07-26)

Demo

There is a boundary condition should the difference between your min and max dates be an odd number. In this case, there is no formal median day, but rather the median would fall in between two days.

Note:

If you're wondering what happens exactly in the edge case, if the low date were today (2018-07-26) and the high date three days away (2018-07-29), then the median would be reported as 2018-07-27.

like image 153
Tim Biegeleisen Avatar answered Sep 10 '25 01:09

Tim Biegeleisen