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"); }
在上面的代码中,我将两个时间变量进行比较以获得相等性,但它为所有类型的输入提供了相同的值-1
解决方法
您需要使用
Date#before(Date),Date#after(Date)和
Date#equals(Date)方法进行基本日期比较.
例如:
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 }
您也可以使用Date#compareTo(Date)方法,但是,您需要相应地解释compareTo方法的输出.
正如文档所说:
The value 0 if the argument Date is equal to this Date; a value less
than 0 if this Date is before the Date argument; and a value greater
than 0 if this Date is after the Date argument.
在你的情况下,你得到-1因为
> new SimpleDateFormat(“HHH:mm:ss”);是错的.应该是新的SimpleDateFormat(“HH:mm:ss”);
> int compare = sqlTime3.compareTo(sqldob1);这个sqlTime3只有时间.日期是你没有提到过的纪元日期,因此,它总是会出现在今天的新Date()之前.
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"); }