Convert mm-dd-yyyy to yyyy-mm-dd

When I grab the current date, I pull the month, day and year, use a string builder and end up with a mm-dd-yyyy format that I put into a textview. When I save data to an sqlitedb, I just grab the date from the textview and insert it. This doesn't work well for date functions as they require yyyy-mm-dd format.

What's the best way to handle this?


Use two SimpleDateFormat instances.

String dateString1 = "16-04-2011";
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dateString1);
String dateString2 = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(dateString2); // 2011-04-16
// ...

But better is to just use java.util.Date all the time to hold the value and apply formatting on the front end only. JDBC offers the PreparedStatement#setDate() to set a java.sql.Date in a SQL string.

preparedStatement.setDate(1, new java.sql.Date(date.getTime()));

From the other side, to get it from the DB, just use ResultSet#getDate() and upcast it to java.util.Date.

Date date = resultSet.getDate("columnname");

Another Approach you could take:

 * This Method Takes an Input String in the format of MM/dd/yyyy
 * and converts it to yyyy-MM-dd
 * @param originalString
 * @return
private String convertMMddyyyyToyyyyMMdd(String originalString) {
    StringBuilder dateBuilder = new StringBuilder();
    dateBuilder = dateBuilder.append(originalString.substring(6)).append("-").append(originalString.substring(0, 2)).append("-").append(originalString.substring(3, 5));
    return dateBuilder.toString();

Need Your Help

How Can I Save A Class Diagram In Intellij?

intellij-idea uml class-diagram

I discovered that in Intellij I can create nice class diagrams by going to New > Diagram > Java Class Diagram. I can do everything that I want to do, except figure out how to save the diagram afte...

MySQL vs PostgreSQL for Web Applications

mysql postgresql

I am working on a web application using Python (Django) and would like to know whether MySQL or PostgreSQL would be more suitable when deploying for production.