Ask Your Question
0

In Java, what is the process for formatting dates from a Mysql database?

asked 2022-06-18 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-10-21 14:00:00 +0000

plato gravatar image

To format dates retrieved from a MySQL database in Java, you can follow these steps:

  1. Retrieve the date/time value from the database using a JDBC ResultSet object.

  2. Create a java.sql.Date or java.util.Date object from the retrieved value. You can use the ResultSet.getDate() or ResultSet.getTimestamp() method for this.

  3. Use a SimpleDateFormat object to format the date as per your requirement. For example, if you want to format the date in "dd/MM/yyyy" format, you can create a SimpleDateFormat object with the pattern "dd/MM/yyyy" and use its format() method to get the formatted date as a String.

Here's an example code snippet that demonstrates this:

import java.sql.*;
import java.text.SimpleDateFormat;

public class DateFormatter {
   public static void main(String[] args) {
      try {
         // Setup JDBC connection to MySQL database
         Connection conn = DriverManager.getConnection(
            "jdbc:mysql://localhost/testdb", "username", "password");

         // Execute SQL query to retrieve date value from database
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT my_date_column FROM my_table");
         rs.next();
         java.sql.Date sqlDate = rs.getDate(1);

         // Convert java.sql.Date to java.util.Date
         java.util.Date utilDate = new java.util.Date(sqlDate.getTime());

         // Format the date using SimpleDateFormat
         SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
         String formattedDate = formatter.format(utilDate);

         // Print the formatted date
         System.out.println("Formatted Date: " + formattedDate);

         // Close JDBC resources
         rs.close();
         stmt.close();
         conn.close();
      } catch (Exception e) {
         System.err.println("Error: " + e.getMessage());
      }
   }
}

Note that you need to replace "mydatecolumn" and "my_table" with the actual column name and table name from your database. Also, replace "testdb", "username" and "password" with the appropriate values for your own database configuration.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-18 11:00:00 +0000

Seen: 17 times

Last updated: Oct 21 '22