Search code examples
javatimestampprepared-statement

How to change date format in timestamp


I'm using preparedStatement to update my sql table. Currently my date format is yyyy-mm-dd how to make it dd-mm-yyyy.

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=1234&useSSL=false");
        con.setAutoCommit(false);
        pstmt = con.prepareStatement(qry);
        sp = con.setSavepoint();
        System.out.println("Enter your name");
        String name = sc.next();
        System.out.println("Enter your contact number");
        long phoneNum = sc.nextLong();
        System.out.println("Purpose of visit");
        String purpose = sc.next();

        pstmt.setString(1, name);
        pstmt.setLong(2, phoneNum);
        pstmt.setString(3, purpose);

         java.sql.Timestamp  dd = new java.sql.Timestamp(new java.util.Date().getTime());
        pstmt.setTimestamp(4, dd);
        pstmt.setTimestamp(5, dd);
        pstmt.executeUpdate();
        con.commit();

Solution

  • The terrible java.sql.Timestamp class is now legacy, no longer needed as of JDBC 4.2 and later. For database work, use OffsetDateTime instead, possibly adjusting to/from Instant or ZonedDateTime.

    LocalDate

    You seem to want only the date, without a time-of-day and without a time zone or offset-from-UTC.

    To represent the date-only, use LocalDate class.

    LocalDate ld = LocalDate.parse( "2019-01-23" ) ;  // By default, parses strings in standard ISO 8601 format: YYYY-MM-DD. 
    

    To capture the current date, specific a time zone.

    ZoneId z = ZoneId.systemDefault() ;
    LocalDate ld = LocalDate.now( z ) ;
    

    To generate text representing that value, use DateTimeFormatter.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
    String output = ld.format( f ) ;
    

    JDBC

    To write a LocalDate object to the database in a column of a data type akin to the standard-SQL type DATE:

    myPreparedStatement.setObject( … , ld ) ;
    

    Retrieve from database:

    LocalDate ld = myResultSet( … , LocalDate.class ) ;