简体   繁体   中英

Find the Median Date between two dates using Java 8

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?

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 .

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

LocalDate median = gerbutsmin.plusDays(ChronoUnit.DAYS.between(gerbutsmin, gerbutsmax) / 2);

"Middle of two dates" is not unambiguously defined - you must decide how to handle dates an odd number of days apart (eg what is the middle date between 1st and 4th of a month, or between 1st and 2nd), and what to do with the time portion of the date object.

The concrete problem with your approach is that dates are not numbers, so you cannot add them and divide them by two. To do that, use the getTime() method to obtain the number of seconds since the epoch, and operate on that:

var middate = new Date((startdate.getTime() + enddate.getTime()) / 2.0);

This will give you the middle between two dates, treating them as points in time.

Click here

LocalDateTime startime = LocalDateTime.now();
LocalDateTime endtime = startime.plusDays(4);
    
long diff = endtime.until(startime, ChronoUnit.MINUTES);
LocalDateTime middleTime = startime.plusMinutes(diff / 2); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM