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.
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
Asked: 2022-06-18 11:00:00 +0000
Seen: 17 times
Last updated: Oct 21 '22
How can Spring Boot and Mysql be utilized for CRUD operations?
What is the method to retrieve the JSON data from a column in SQL?
What is the process for initializing Java UDFs in Spark?
How can set the Project Title in the Doxygen Configuration File?
How can I convert Double to Long in Java?
Can I add a default Parameter for a Method in Java like int calculate(int x, int y=2)?
How can the rejection of the class text_plain from JavaMail API due to a VerifyError be confirmed?