Compare twice in Java more or less

Date date1= new java.util.Date();
Date date1= new java.util.Date();
                  java.sql.Date sqldob = new java.sql.Date(date1.getTime());
                  System.out.println("date" +sqldob);

                  Time sqldob1 = new Time(date1.getTime());
                  System.out.println("User Time: " +sqldob1);
                  String yourTime="09:30:00"; 

                  SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
                  Date yourDate = ra.parse(yourTime);
                  Time sqlTime3 = new Time(yourDate.getTime());
                  System.out.println("your time"+sqlTime3);

                  if(sqldob1.before(sqlTime3)){
                     sqldob1 = sqlTime3; 
                     System.out.println("inside loop");
                  }

In the above code, I compare the two time variables for equality, but it provides the same value of - 1 for all types of input

Solution

You need to use the date #before (date), date #after (date) and date #equals (date) methods for basic date comparison

For example:

Date d1 = new Date();
Date d2 = new Date();

if(d1.after(d2)){
    // Do something
}

if(d1.before(d2)){
    // Do something
}

if(d1.equals(d2)){
    // Do something
}

You can also use the date #compareto (date) method, but you need to interpret the output of the CompareTo method accordingly

As the document says:

In your case, you get - 1 because

> new SimpleDateFormat(“HHH:mm:ss”); It's wrong Should be the new simpledateformat ("HH: mm: SS"); > int compare = sqlTime3. compareTo(sqldob1); This sqltime3 only has time The date is an era date you haven't mentioned, so it always appears before today's new date ()

Your solution: – (I hope this will solve your problem)

java.util.Date date1= new java.util.Date();

Time sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +sqldob1);

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,19); // Your hour
cal.set(Calendar.MINUTE,30); // Your Mintue
cal.set(Calendar.SECOND,00); // Your second

Time sqlTime3 = new Time(cal.getTime().getTime());
System.out.println("your time: "+sqlTime3);

if(sqldob1.before(sqlTime3)){
   sqldob1 = sqlTime3; 
   System.out.println("inside loop");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>