This would be an example to convert a String
to Date
, 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;
try {
String stringDate = "Junio 8, 2016";
Locale espanol = new Locale("es", "ES");
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", espanol);
Date date = format.parse(stringDate); //Obtienes el String como Date.
Log.i("INFO", date.toString());
} catch (ParseException e) {
e.printStackTrace();
}
you must bear in mind that from the beginning you must have a String
containing the text in a format that can be converted to Date
.
Another way can be simply, without using Locale :
String stringDate= "Junio 8, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date = format.parse(stringDate);
Update:
It seems to me that this question is "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 another.
The first thing you have to do is define what format you should enter in your EditText (you could add a validator to ensure users are not mistaken) and also define the format you want to obtain.
in your case you need to convert
2016-6-8
to 2016-06-08
we can do it this way through this method, which you can use to define any input and output format:
private static String convierteFecha(String stringFechaEntrada, String formatoEntrada, String formatoSalida){
Log.i("TAG", "stringFechaEntrada :" + stringFechaEntrada);
//Definimos formato del string que ingresamos.
SimpleDateFormat sdf = new SimpleDateFormat(formatoEntrada);
try {
Date date = sdf.parse(stringFechaEntrada);
//Definimos formato del string que deseamos obtener.
sdf = new SimpleDateFormat(formatoSalida);
String stringFechaSalida = sdf.format(date);
Log.i("TAG", "stringFechaSalida :" + stringFechaSalida);
Date dateSalida = sdf.parse(stringFechaSalida);
//Log.i("TAG", "dateSalida :" + dateSalida);
return stringFechaSalida;
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
If we call the previous method:
Log.i("INFO : " , convierteFecha("2016-6-8", "yyyy-MM-dd", "yyyy-MM-dd"));
we can obtain as a result 2016-06-08
With the same method you can change the output format:
Log.i("INFO : " , convierteFecha("2016-6-8", "yyyy-MM-dd", "dd/MM/yyyy hh:mm:ss.SSS"));
to get 08/06/2016 12:00:00.000
even change the entry data
Log.i("INFO : " , convierteFecha("18 Apr 2012", "dd MMM yyyy", "dd/MM/yyyy hh:mm:ss.SSS"));
getting 18/04/2012 12:00:00.000