Search code examples
javaswingsqlitejdbcjcalendar

How to change sql date format in java


I am using JDBC connectivity & Java Swing UI and there I used SqLite DB.
Here I have a java component that is jCalender to pickup date & i pick the date into String.


Firstly I convert string into java.util date then i convert java.util.date to java.sql.date but my date string format is "dd/MM/YYYY" &

Then
DateFormat format = new SimpleDateFormat("dd/MM/YYYY", Locale.ENGLISH);

and I set specific date format which written above. but there still problem when I search record between date.

Here I attached a copy of code plz guyz help me it is very important.



    String from_date = ((JTextField) txt_bilty_date_start.getDateEditor().getUiComponent()).getText();
    String to_date = ((JTextField) txt_bilty_date_end.getDateEditor().getUiComponent()).getText();

    DateFormat format = new SimpleDateFormat("dd/MM/YYYY", Locale.ENGLISH);
    Date date1 = format.parse(from_date);
    Date date2= format.parse(to_date);

    java.sql.Date sqlDate1 = new java.sql.Date(date1.getTime());
    java.sql.Date sqlDate2 = new java.sql.Date(date2.getTime());

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");

    System.out.println("\t\tafter change date");
    System.out.println(sdf.format(sqlDate1));
    System.out.println(sdf.format(sqlDate2));

    String sql = "select * from employee where record_date BETWEEN '"+sdf.format(sqlDate1)+"' AND '"+sdf.format(sqlDate2)+"' ";

    pst=conn.prepareStatement(sql2);
    rs = pst.executeQuery();
    tbl_employee.setModel(DbUtils.resultSetToTableModel(rs));

Solution

  • Assuming your record_date is a SQL date in your database (and not some varchar), try it like this with a proper PreparedStatement.

    String sql = "select * from employee where record_date BETWEEN ? AND ?";
    pst=conn.prepareStatement(sql2);
    pst.setDate(1, sqlDate1);
    pst.setDate(2, sqlDate2);
    rs = pst.executeQuery();
    

    Note that the whole try / catch / check for closed in finally has become much more easier with try-with-resource introduced in Java 7.

    If your date is a varchar you will need to reverse the order of your fields to have the most significant field up front - yyyy MM dd in some fashion. Only then will the results of a String/VARCHAR compare work like they should on string representations of strings.