java.util.Date vs java.sql.Date

前端 未结 7 2248
青春惊慌失措
青春惊慌失措 2020-11-22 05:13

java.util.Date vs java.sql.Date: when to use which and why?

7条回答
  •  野性不改
    2020-11-22 05:44

    The java.util.Date class in Java represents a particular moment in time (e,.g., 2013 Nov 25 16:30:45 down to milliseconds), but the DATE data type in the DB represents a date only (e.g., 2013 Nov 25). To prevent you from providing a java.util.Date object to the DB by mistake, Java doesn’t allow you to set a SQL parameter to java.util.Date directly:

    PreparedStatement st = ...
    java.util.Date d = ...
    st.setDate(1, d); //will not work
    

    But it still allows you to do that by force/intention (then hours and minutes will be ignored by the DB driver). This is done with the java.sql.Date class:

    PreparedStatement st = ...
    java.util.Date d = ...
    st.setDate(1, new java.sql.Date(d.getTime())); //will work
    

    A java.sql.Date object can store a moment in time (so that it’s easy to construct from a java.util.Date) but will throw an exception if you try to ask it for the hours (to enforce its concept of being a date only). The DB driver is expected to recognize this class and just use 0 for the hours. Try this:

    public static void main(String[] args) {
      java.util.Date d1 = new java.util.Date(12345);//ms since 1970 Jan 1 midnight
      java.sql.Date d2 = new java.sql.Date(12345);
      System.out.println(d1.getHours());
      System.out.println(d2.getHours());
    }
    

提交回复
热议问题