简体   繁体   中英

String Date conversion into sql date format MM/dd/yyyy?

public void setEmployeeDetails(String month,String year,String day) throws

SQLException, ParseException
{

        String sql="INSERT INTO EmployeeDetails (SiteName,EmployeeName,EmployeePhoneNumber,Date) VALUES(?,?,?,?)"; 
          pStmt = conn.prepareStatement(sql) ;

             String date=month+"/"+day+"/"+year;
             SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
             java.util.Date parsed = format.parse(date);
             java.sql.Date sql_date = new java.sql.Date(parsed.getTime());
             System.out.println(sql_date);
         }
    public static void main(String args[]) throws SQLException, ClassNotFoundException, ParseException{
        Employee_Details_DAO e=new Employee_Details_DAO();
        e.setEmployeeDetails("12","2006","10");
    }

I want to convert string date as format MM/ddd/yyy to sql ms access date format. But I got the output as 2006-12-10 but output should be as 12/10/2006

If System.out.println(sql_date); is displaying the date value as 2006-12-10 it is because it is using a default yyyy-mm-dd format, either from Java or from the operating system. It doesn't mean that the date is "wrong", it is just being displayed in a different way.

Always remember:

Date values do NOT have formats. They are just (numeric) values that correspond to a particular date.

[String] Representations of Dates do have a format. However, the format does not affect the value in any way. Whether it's 2006-12-25 or 12/25/2006 or December 25, 2006 or 2006 décembre 25 the Date value is still the same.

So, you don't need to worry about using any particular format for a Date parameter, just pass the value itself:

try (
        Connection conn = DriverManager.getConnection(connStr);
        PreparedStatement ps = conn.prepareStatement(
                "INSERT INTO EmployeeDetails ([Date]) VALUES (?)")) {
    String month = "12";   //
    String year = "2006";  // sample data
    String day = "10";     //
    ps.setDate(1, java.sql.Date.valueOf(year + "-" + month + "-" + day));
    ps.executeUpdate();
}
 System.out.println(format.format(sql_date));//12/10/2006

java.sql.Date is a sub-class of java.util.Date . So we can format for java.sql.Date same as java.util.Date .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM