0

I need to convert a string to date to allow me insert information in mysql table:

I tried this:

System.out.println("Escribe la fecha de nacimiento de socio:");
//Traduction to english:        set the date of birthday //

String fechaSocio  = sc.next();

Date fecha = null;
try {
  fecha = new SimpleDateFormat("ddMMyyyy").parse(fechaSocio);
} catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

but It's converting like that: Thu Mar 21 00:00:00 CET 1996

I need to convert to this :

01-01-1987 or 01011987

public class SocioDao {
static ClaseConexion conexion = new ClaseConexion();

public void insertar(Socio misocio){

System.out.println(misocio.getDATA_NAIXEMENT());
System.out.println("..........................");


  try {

        Statement statuo = conexion.getConnection().createStatement();


        statuo.executeUpdate("insert into socis(CODI_SOCI,DNI,NOM,COGNOMS,"
                + "DATA_NAIXEMENT,ADRECA,POBLACIO,TELEFON) values ('"
                + misocio.getCODI_SOCI() + "','" + misocio.getDNI()
                + "',' " + misocio.getNOM() + "','" + misocio.getCOGNOMS()
                + "','" + misocio.getDATA_NAIXEMENT() + "','"
                + misocio.getADREÇA() + "','" + misocio.getPOBLACIO()
                + "','" + misocio.getTELEFON() + "')");

        statuo.close();
        conexion.desconectar();
        System.out.println("Socio añadido correctamente");

    } catch (Exception e) {
        System.out.println("No se puede añadir un nuevo socio");




    }

}

}

2
  • You've only shown us the parsing. You haven't shown us how you try to set the date in the MySQL query. Commented Mar 8, 2014 at 20:46
  • Where are getting Thu Mar 21 00:00:00 CET 1996 from? Commented Mar 8, 2014 at 20:47

2 Answers 2

4

It seems like you are trying to pass a Date as a String in your MySQL query.

Don't. Instead use the appropriate date setter method in the PreparedStatement class.

Remember, a Date doesn't have a format. A format is only for displaying a date.

Sign up to request clarification or add additional context in comments.

1 Comment

See this other answer by BalusC for an example of what this answer suggests.
0

Use mysql function if you are trying to insert date in database..

for example:

INSERT INTO test (sampledate) VALUES (CURDATE());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.