I am new to programming Android and I am trying to calculate the difference between two dates to show it in a TextView but I do not achieve it
I am new to programming Android and I am trying to calculate the difference between two dates to show it in a TextView but I do not achieve it
Let's say that you have your dates in two TextView or in two variables, what you could do is convert that string into an integer and make a comparison.
Here is a small example
String fecha1 = "22/08/2017";
String fecha2 = "20/08/2016";
//Con la función replace reemplazamos las barras / por null o nada (en pocas palabras las quitamos)
String nuevaFecha1 = fecha1.replace("/", ""); //el valor seria 22082017
String nuevaFecha2 = fecha2.replace("/", ""); //el valor seria 20082016
//Variables que almacenan los valores de las fechas anteriores pero convertidas a enteros con la función Integer.valueOf(valor_cadena)
int valorFecha1 = Integer.valueOf(nuevaFecha1); // convertimos el String 22082017 a int 22082017
int valorFecha2 = Integer.valueOf(nuevaFecha2); // convertimos el String 20082016a int 20082016
//Esta variable almacenara la fecha mayor comparada de los dos valores
String fechaMayor;
//Comparamos cual de las dos fechas es mayor
if(valorFecha1 > valorFecha2){
fechaMayor = String.valueOf(valorFecha1);
}else{
fechaMayor = String.valueOf(valorFecha2);
}
//Imprimimos el valor en Log de la fecha mayor, solo cambia para que este valor cargue en tu TextView o EditText
Log.v("TAG_FECHA_MAYOR", fechaMayor);
Maybe this code will help you.
This is a function to obtain the date that the user chooses:
public void obtenerFecha(){
//Calendario para obtener fecha & hora
public final Calendar c = Calendar.getInstance();
final int mes = c.get(Calendar.MONTH);
final int dia = c.get(Calendar.DAY_OF_MONTH);
final int anio = c.get(Calendar.YEAR);
DatePickerDialog recogerFecha = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
int mesActual = month + 1;
String diaFormateado = (dayOfMonth < 10)? "0" + String.valueOf(dayOfMonth):String.valueOf(dayOfMonth);
String mesFormateado = (mesActual < 10)? "0" + String.valueOf(mesActual):String.valueOf(mesActual);
mEtFecha.setText(diaFormateado + "/" + mesFormateado +"/"+ year);
}
},anio, mes, dia);
recogerFecha.show();
}
With this you can store it in mEtDate, which would be an EditText or TextView.