How to convert java.util.Date to java.sql.Date?

后端 未结 18 2324
梦如初夏
梦如初夏 2020-11-22 01:44

I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.

I was surprised to find that it couldn\'t do the conver

相关标签:
18条回答
  • 2020-11-22 02:38

    I think the best way to convert is:

    static java.sql.Timestamp SQLDateTime(Long utilDate) {
        return new java.sql.Timestamp(utilDate);
    }
    
    Date date = new Date();
    java.sql.Timestamp dt = SQLDateTime(date.getTime());
    

    If you want to insert the dt variable into an SQL table you can do:

    insert into table (expireAt) values ('"+dt+"');
    
    0 讨论(0)
  • 2020-11-22 02:39

    Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date

    java.util.Date utilDate = "Your date"
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    final String stringDate= dateFormat.format(utilDate);
    final java.sql.Date sqlDate=  java.sql.Date.valueOf(stringDate);
    
    0 讨论(0)
  • 2020-11-22 02:41

    If you are usgin Mysql a date column can be passed a String representation of this date

    so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement

    here is the code illustration:

    private String converUtilDateToSqlDate(java.util.Date utilDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sqlDate = sdf.format(utilDate);
        return sqlDate;
    }
    

    String date = converUtilDateToSqlDate(otherTransaction.getTransDate());

    //then pass this date in you sql statement

    0 讨论(0)
  • 2020-11-22 02:43

    Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.

    java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
    java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)
    
    0 讨论(0)
  • 2020-11-22 02:45
    java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
    

    Here javaDate is the instance of java.util.Date

    0 讨论(0)
  • 2020-11-22 02:46

    Method for comparing 2 dates (util.date or sql.date)

     public static boolean isSameDay(Date a, Date b) {
        Calendar calA = new GregorianCalendar();
        calA.setTime(a);
    
        Calendar calB = new GregorianCalendar();
        calB.setTime(b);
    
        final int yearA = calA.get(Calendar.YEAR);
        final int monthA = calA.get(Calendar.MONTH);
        final int dayA = calA.get(Calendar.DAY_OF_YEAR);
    
        final int yearB = calB.get(Calendar.YEAR);
        final int monthB = calB.get(Calendar.MONTH);
        final int dayB = calB.get(Calendar.DAY_OF_YEAR);
    
        return yearA == yearB && monthA == monthB && dayA == dayB;
    }
    
    0 讨论(0)
提交回复
热议问题