Java Data Type How to - Compare Calendar's time to java.sql.Time object


We would like to know how to compare Calendar's time to java.sql.Time object.


import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//from ww w  .ja  va 2 s . c  o m
public class Main {

   * Method to convert a calendar object to java's epoch date keeping only the
   * time information
  public static Date toEpochDate(Calendar calendar) {
    return new Date(Time.valueOf(
        new SimpleDateFormat("HH:mm:ss").format(calendar.getTime())).getTime());

  public static void main(String[] args) {
    Calendar someTime = Calendar.getInstance();
    someTime.set(Calendar.HOUR_OF_DAY, 17);
    someTime.set(Calendar.MINUTE, 0);
    someTime.set(Calendar.SECOND, 0);

    // convert it to java epoch date
    Date someDate = toEpochDate(someTime);

    // create a date object from java.sql.Time
    Date fromSqlTime = new Date(Time.valueOf("17:00:00").getTime());

    // now do the comparison
    System.out.println("Some Date: " + someDate.toString());
    System.out.println("Sql Time: " + fromSqlTime.toString());
    System.out.println("Are they equal? " + someDate.equals(fromSqlTime));

The code above generates the following result.