Get the remaining time between two Date dates on Android

2

I make an Application where I need to obtain the remaining time for the day of an event, using the class CountDownTimer I get a counter for days and dates but I can not think of how to get the remaining time.

For this I have two dates established by means of two Date and I need to know the time remaining between them, for the date of the event I have the format:

Date(int year, int month, int day, int hour, int minute, int second);

And for the current time I simply generate a new date

Date date = new Date();

How can I get the remaining time in days, hours, minutes and seconds.

My code in which I only have the counter with the current time until the event:

First declare the variables:

private TextView countDown;
private CountDownTimer countDownTimer;
private long initialTime =
            DateUtils.DAY_IN_MILLIS * 110 +
            DateUtils.HOUR_IN_MILLIS * 9 +
            DateUtils.MINUTE_IN_MILLIS * 3 +
            DateUtils.SECOND_IN_MILLIS * 42;

and then handle it in CountDownTimer :

       countDownTimer = new CountDownTimer(initialTime, 1000) {
            StringBuilder time = new StringBuilder();

            @Override
            public void onTick(long millisUntilFinished) {
                time.setLength(0);
                // Use days if appropriate
                if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) {
                    long count = millisUntilFinished / DateUtils.DAY_IN_MILLIS;
                    if(count > 1)
                        time.append(count).append(" Dias ");
                    else
                        time.append(count).append(" Dia ");

                    millisUntilFinished %= DateUtils.DAY_IN_MILLIS;
                }

                time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished / 1000d)));
                countDown.setText(time.toString());
            }

            @Override
            public void onFinish() {
                countDown.setText(DateUtils.formatElapsedTime(0));
                countDown.setText("Dia del evento");
            }


        }.start();
    
asked by Max Sandoval 02.06.2016 в 05:43
source

3 answers

4

First you have to get the difference in milliseconds:

long diff = date1.getTime() - date2.getTime();

Then do the operations to know the difference in the unit that you require:

long segundos = diff / 1000;
long minutos = segundos / 60;
long horas = minutos / 60;
long dias = horas / 24;

You must consider that when making the entire division, an error is introduced by truncation.

    
answered by 02.06.2016 / 06:27
source
1

With this method you can achieve it and it is similar to what you are doing:

public String getDiferencia(Date fechaInicial, Date fechaFinal){

    long diferencia = fechaFinal.getTime() - fechaInicial.getTime();

    Log.i("MainActivity", "fechaInicial : " + fechaInicial);
    Log.i("MainActivity", "fechaFinal : " + fechaFinal);

    long segsMilli = 1000;
    long minsMilli = segsMilli * 60;
    long horasMilli = minsMilli * 60;
    long diasMilli = horasMilli * 24;

    long diasTranscurridos = diferencia / diasMilli;
    diferencia = diferencia % diasMilli;

    long horasTranscurridos = diferencia / horasMilli;
    diferencia = diferencia % horasMilli;

    long minutosTranscurridos = diferencia / minsMilli;
    diferencia = diferencia % minsMilli;

    long segsTranscurridos = diferencia / segsMilli;

    return "diasTranscurridos: " + diasTranscurridos + " , horasTranscurridos: " + horasTranscurridos +
            " , minutosTranscurridos: " + minutosTranscurridos + " , segsTranscurridos: " + segsTranscurridos;


}

We determine the dates on which we want to obtain the difference:

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
    Date fechaI = null, fechaF = null;
    try {
        fechaI = simpleDateFormat.parse("1/6/2016 12:20:12");
         //fechaF puede ser la fecha actual o tu puedes asignarala,
         //por ejemplo: fechaF = simpleDateFormat.parse("2/6/2016 15:40:42");
         fechaF = new Date(System.currentTimeMillis());
    } catch (ParseException e) {
        e.printStackTrace();
    }

From the values we execute the getDiferencia() method with the start and end dates:

  Log.i(TAG,  getDiferencia(fechaI , fechaF));

The method internally prints the start and end date, so you can verify the values:

fechaInicial : Wed Jun 01 00:20:12 CDT 2016
fechaFinal : Thu Jun 02 11:32:16 CDT 2016

and get a string with the values of the difference:

diasTranscurridos: 1 , horasTranscurridos: 11 , minutosTranscurridos: 12 , segsTranscurridos: 4
    
answered by 02.06.2016 в 18:39
0

I add my complete solution to my problem for future questions.

First Declare the variables to use.

private TextView countDown;
private CountDownTimer countDownTimer; 
private Date eventDate, presentDate;
private Calendar calendar;
private long initialTime;

Then we initialize the variable calendar with a new instance and send the date of our future event.

 calendar = Calendar.getInstance();
 calendar.set(Calendar.YEAR, 2016);
 calendar.set(Calendar.MONTH, Calendar.AUGUST);
 calendar.set(Calendar.DAY_OF_MONTH, 20);
 calendar.set(Calendar.HOUR_OF_DAY, 7);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.SECOND, 0);

We now initialize the variables of Date that are eventDate = day of the event and presentDate = current day, the first gets its value from the calendar created earlier and the second from the current day.

 eventDate = calendar.getTime();
 presentDate = new Date();

Next step we obtain the difference in milli seconds by first assigning the day of the event and then the current day, we save the results in a variable type long and send them to Log to verify that the result is not negative, if so, the dates are misassigned.

long diff = eventDate.getTime() - presentDate.getTime();
Log.d("dateEvent", String.valueOf(eventDate));
Log.d("dateActual", String.valueOf(presentDate));
Log.d("diff", String.valueOf(diff)); 

Next step we obtain the equivalence in days, hours, minutes and seconds with these simple mathematical operations, all the results are stored in variables type long .

This will give us as a result, for example:

  

diff equals 5 days 3 hours 23 minutes and 5 seconds

/**
 * Explicación:
 * segundos = (milisegundos / 1 segundo en milisegundos) mod 60 segundos de un minuto
 */
long seconds =(diff/1000)%60;
long minutes=(diff/(1000*60))%60;
long hours=(diff/(1000*60*60))%24;
long days=(diff/(1000*60*60*24))%365;

As I need to do a counter to the date, I initialize the variable ìnitialTime with the value of the difference diff .

 initialTime = diff;

And then I assign the values to the constructor to initialize the variable countDownTimer :

countDownTimer = new CountDownTimer(initialTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

                int days = (int) ((millisUntilFinished / 1000) / 86400);
                int hours = (int) (((millisUntilFinished / 1000)
                        - (days * 86400)) / 3600);
                int minutes = (int) (((millisUntilFinished / 1000)
                        - (days * 86400) - (hours * 3600)) / 60);
                int seconds = (int) ((millisUntilFinished / 1000) % 60);

                String countDownText = String.format("%2d Dias %2d Hr %2d Min %2d Seg", days, hours, minutes, seconds);
                countDown.setText(countDownText);
            }

            @Override
            public void onFinish() {
                countDown.setText(DateUtils.formatElapsedTime(0));
            }

        }.start();

With this the CountDownTimer works from the current date to the event.

    
answered by 02.06.2016 в 17:20