1 | initial version |
To format dates retrieved from a MySQL database in Java, you can follow these steps:
Retrieve the date/time value from the database using a JDBC ResultSet object.
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.
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.