Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing and converting Datetime format from csv file to mysql in Java
    text
    copied!<p>I have a csv file in which the Datetime column is defined in "DD-MM-YYYY HH:MM" format. But the problem is MySQL accepts Datetime type as "YYYY-MM-DD HH:MM" only. I want to convert the format given in csv file to format defined by MySQL but I am not able to do it.I tried to covert the format in excel but first there is no datetime format in excel and if I split the column into two then it changes the structure of my file and thus not able to insert in database.So, the only option is to use Java program and change the format before inserting. Can anyone provide me some help in this regard?</p> <p>This is my class which is getting called for converting the formats but I do not know what is wrong here and whether it is sufficient or I am missing something.(This class is getting accessed from another program.) </p> <pre><code>import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DateUtil { // List of all date formats that we want to parse. // Add your own format here. private static List&lt;SimpleDateFormat&gt; dateFormats = new ArrayList&lt;SimpleDateFormat&gt;() { private static final long serialVersionUID = 1L; { // add(new SimpleDateFormat("M/dd/yyyy")); // add(new SimpleDateFormat("dd.M.yyyy")); // add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a")); // add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a")); // add(new SimpleDateFormat("dd.MMM.yyyy")); add(new SimpleDateFormat("dd-MM-yyyy hh:mm")); add(new SimpleDateFormat("yyyy-MM-dd hh:mm")); } }; /** * Convert String with various formats into java.util.Date * * @param input * Date as a string * @return java.util.Date object if input string is parsed * successfully else returns null */ public static Date convertToDate(String input) { Date date = null; if(input == null ) { return null; } for (SimpleDateFormat format : dateFormats) { try { format.setLenient(false); date = format.parse(input); } catch (ParseException e) { //Shhh.. try other formats } if (date != null) { break; } } return date; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload