Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
Roger Avatar asked Apr 16 '11 16:04

Roger


People also ask

How do I change the format of dd-mm-yyyy to dd-mm-yyyy?

First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay. It will format the dates you specify.

How do I convert date from yyyy-mm-dd in Excel?

Convert date to yyyy-mm-dd format with formula Select a blank cell next to your date, for instance. I1, and type this formula =TEXT(G1, "yyyy-mm-dd"), and press Enter key, then drag AutoFill handle over the cells needed this formula. Now all dates are converted to texts and shown as yyyy-mm-dd format.

How do I convert mm/dd/yyyy to text?

Convert Date to Text using Text to ColumnGo to Data –> Data Tools –> Text to Column. This would instantly convert the dates into text format. Note: There is a difference in the format of the dates in the two columns. While the original format had dd mmm, yyyy format, the result is dd-mm-yyyy.


1 Answers

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");
like image 135
BalusC Avatar answered Sep 26 '22 22:09

BalusC