Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isAfter isBefore Java 8 LocalDateTime One Day Different

I want to compare two dates with today date. Does isAfter and isBefore best for this? isAfter and isBefore cant detect one day changes. Lets say:

If today is 20 Nov. I put in range 20 Nov-21 Nov.

if(todayDate.isAfter(startDate) && todayDate.isBefore(endDate))
{
  // task
}

This code wont detect that today is in range. OR / || is not applicable because I have a set of range to be tested. Any idea on this?

like image 241
SkyvrawleR Avatar asked Nov 20 '15 00:11

SkyvrawleR


1 Answers

This will solve it: Just add a check for whether today's date it either the start or end date which you will have to implement yourself

if( (todayDate.isAfter(startDate) && todayDate.isBefore(endDate) ) || (todayDate.isEqual(startDate) || todayDate.isEqual(endDate) )
{
     // task
}

This is because isAfter and isBefore are both strict.

Edit: A better more logical solution:

if(!todayDate.isAfter(endDate) && !todayDate.isBefore(startDate))
{
    // task
}

By negating isAfter, it becomes endDate or before.

By negating isBefore, it becomes startDate or after.

like image 88
jiaweizhang Avatar answered Sep 28 '22 08:09

jiaweizhang