Hello, I have a question about the best way to convert a string to a date in android.
fechauso = (EditText)findViewById(R.id.txt_fechadeuso);
String fechausoo = fechauso.getText().toString();
I want to convert it to date because just as I have it when saving it in a mysql database in a Date type field, it saves it like this:
0000-00-00
I am trying to solve it in the following way:
String newfecha = fechauso.getText().toString();
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date fecha = sdf.parse(newfecha);
} catch (ParseException e){
e.printStackTrace();
}
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("fecha_prestamo",newfecha.trim()));
but it gives me the following error:
Incopatible types:
Required: java.sql.Date;
Found: java.util.Date
amount as follows:
import java.sql.Date;
but even so it continues to mark the error, I apologize if I'm asking something very basic, but seriously I'm lost...
This would be an example to convert a
String
toDate
, using the classes:import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.text.DateFormat; import java.util.Locale;
You must take into account that as input you must have a
String
containing the text in a format that can be converted toDate
.Another way can be simply, without using Locale :
Update: It seems to me that this question fell "short", what you need is not only to convert: "String to Date in Android", what you need is, based on a date text entered in an EditText, change the format to other. The first thing you have to do is define what format should be entered in your EditText (you could add a validator to ensure users don't make mistakes) and also define the format you want to obtain.
in your case you need to convert
2016-6-8
to2016-06-08
we can do it this way using this method, which you can use to define any input and output format:If we call the above method:
we can get as a result
2016-06-08
With the same method you can change the output format:
to get
08/06/2016 12:00:00.000
even change the input data
getting
18/04/2012 12:00:00.000
As I see the situation, you are doing the parse correctly from String to Date. The error I see is that you need a sql.Date to save in your database, the SimpleDateFormat returns a util.Date, the simple solution is to parse util.Date to sql.Date, which would be something as simple as .
or even better
Already with your date in sql.Date you can save it in the database.
Annex capture of my code and placement of the same: