A simple method to convert a date from MySQL format to the Italian format and vice versa
Sometimes, it is necessary to convert the format of a date returned by the MySQL database in a different format, such as Italian. The following example shows a simple method to convert a date from MySQL format to the Italian format and vice versa.
public class ConvertDateFormat {
public static void main(String[] args)
{
String mysqlDate = "2014-05-01";
String italianDate = "16/08/2015";
System.out.println("MySQL -> Italian");
System.out.println("MySQL date is: " + mysqlDate);
System.out.println("Italian date is: " + convertDateToItalianFormat(mysqlDate));
System.out.println();
System.out.println("Italian -> MySQL");
System.out.println("Italian date is: " + italianDate);
System.out.println("MySQL date is: " + convertDateToMySQLFormat(italianDate));
}
private static String convertDateToItalianFormat(String date) {
String year = date.substring(0, 4);
String month = date.substring(5, 7);
String day = date.substring(8, 10);
String convertsDate = day + "/" + month + "/" + year;
return convertsDate;
}
private static String convertDateToMySQLFormat(String date) {
String day = date.substring(0, 2);
String month = date.substring(3, 5);
String year = date.substring(6, 10);
String convertsDate = year + "-" + month + "-" + day;
return convertsDate;
}
}
Result:
>java -cp . ConvertDateFormat
MySQL -> Italian
MySQL date is: 2014-05-01
Italian date is: 01/05/2014
Italian -> MySQL
Italian date is: 16/08/2015
MySQL date is: 2015-08-16
>Exit code: 0