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

When I take the current date, I drag the month, day and year, use the line builder and get the mm-dd-yyyy format, which I paste into the text box. When I save the data in sqlitedb, I just take the date from the text box and paste it. This does not work for date functions, since they require the format yyyy-mm-dd.

What is the best way to handle this?

+5
source share
2 answers

Use two SimpleDateFormatinstances.

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 itโ€™s best to use it java.util.Dateall the time to keep the value and apply formatting only on the front side. JDBC suggests PreparedStatement#setDate()installing java.sql.Datein an SQL string.

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

, , ResultSet#getDate() java.util.Date.

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

, :

/**
 * 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();
}
0

All Articles