Difference between two date strings in java

I am trying to calculate the difference between two date strings, both of which are taken from the user through the html form in the format (yyyy / MM / dd) Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd"); 
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;       

    if( diff<3 || diff>3)
    {
        return true;
    }
    else 
    {       
        return false;
    }       
 }

Now I use the if condition to report an error on my webpage if the difference between the date is not 3. Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required maps to "date check"

So, the problem is the "validation date" error for any date string value.

0
source share
6 answers

you will never get a difference of exactly 3 milliseconds between two dates obtained from the formatted string yyyy / MM / dd (maximum accuracy will be 24 hours)

if you want to use the difference of 3 days 24*60*60*1000for the scaling factor of the values

+1

, 3 , . 3 , 3 * 86400 * 1000. , , .

+2

diff < 3 || diff > 3 diff!= 3, diff . .

+1

1 , 86.000.000 , , 3 .

getTime() ms " ", 1/1000 .

diff < 3 || diff > 3

diff != 3

, 3 , / .

+1

java.util.Calendar add, , compareTo, . .

+1

TL;DR

java.lang.Math.abs (
    ChronoUnit.DAYS.between(
        LocalDate.parse( "2017/01/23".replace( "/" , "-" ) ) ,
        LocalDate.parse( "2017/02/14".replace( "/" , "-" ) ) 
    )
) > 3L

java.time

java.time, (Date, Calendar, ).

ISO 8601 : YYYY-MM-DD. , .

String inputA = "2017/01/23".replace( "/" , "-" ) ;
String inputB = "2017/02/14".replace( "/" , "-" ) ;

java.time / . .

LocalDate ldA = LocalDate.parse( inputA );
LocalDate ldB = LocalDate.parse( inputB );

, +/- , . , . ChronoUnit enum.

long daysBetween = ChronoUnit.DAYS.between( ldA , ldB );

, . , , ± 3. java.lang.Math abs .

ChronoUnit.DAYS.between long. , , . L, , 3L long. 3 int (32-) long (64-), 3L.

if( abs( daysBetween ) > 3L ) { … }

java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .

0

All Articles