How to convert a Date value to string in JDBC?


The toString() method of the java.sql.Date class returns the escape format: yyyy-mm-dd of the date represented by the current date object. Using this method you can convert a Date object to a String.

Date date = rs.getDate("Dispatch_Date");
date.toString());

Assume we have a table named dispatch_data 3 records as shown below:

+--------------+------------------+---------------+----------------+
| Product_Name | Name_Of_Customer | Dispatch_Date | Location       |
+--------------+------------------+---------------+----------------+
| KeyBoard     | Amith            | 1981-12-05    | Hyderabad      |
| Ear phones   | Sumith           | 1981-04-22    | Vishakhapatnam |
| Mouse        | Sudha            | 1988-11-05    | Vijayawada     |
+--------------+------------------+---------------+----------------+


Following JDBC program establishes connection with the database retrieves the contents of the dispatch_data table, converts the date objects into String values using the toString() method and displays the contents of the table along with the Date values (which are converted into String format):

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DateToString {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Creating Statement object
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from dispatch_data");
      //Retrieving values
      while(rs.next()) {
         System.out.println("Product Name: "+rs.getString("Product_Name"));
         System.out.println("Name Of The Customer: "+rs.getString("Name_Of_Customer"));
         //Retrieving the date
         Date date = rs.getDate("Dispatch_Date");
         //Converting Date object to String
         System.out.println("Date: "+date.toString());
         System.out.println();
      }
   }
}

Output

Connection established......
Product Name: KeyBoard
Name Of The Customer: Amith
Date: 1981-12-05

Product Name: Ear phones
Name Of The Customer: Sumith
Date: 1981-04-22

Product Name: Mouse
Name Of The Customer: Sudha
Date: 1988-11-05


Updated on: 30-Jul-2019

914 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements