DonkeyTheKong
DonkeyTheKong

Reputation: 37

How do you create a coutdown on a specific date?

How do you create a coutdown on a specific date?

I want to create a countdown that counts down from the current date to a specific date. I've also tried stackoverflow code. However, I had an exorbitant number of days or that the timer didn't work.

My TimeFragment.java

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.kalirobot.daring.R;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;


public class TimeFragment extends Fragment {

    private TextView timer;
    public static TimeFragment newInstance() {
        return new TimeFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_time, container, false);
        timer = view.findViewById(R.id.textView3);

        Calendar start_calendar = Calendar.getInstance();
        Calendar end_calendar = Calendar.getInstance();
        // end DAY
        end_calendar.set(2020, 8, 23);

        long start_millis = start_calendar.getTimeInMillis();
        long end_millis = end_calendar.getTimeInMillis();
        long total_millis = (end_millis - start_millis);


        CountDownTimer cdt = new CountDownTimer(total_millis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
                millisUntilFinished -= TimeUnit.DAYS.toMillis(days);
                long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
                millisUntilFinished -= TimeUnit.HOURS.toMillis(hours);
                long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
                millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes);
                long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
                timer.setText(days + ":" + hours + ":" + minutes + ":" + seconds);
            }

            @Override
            public void onFinish() {
                timer.setText("Finish!");
            }
        };
        cdt.start();
        return view;
    }
}

The output now is 51:23:59:41 in the timer while 21 would be the expected value for the "days" portion instead of 51.

Hint - If you want a countdown with synchronized time

GitHub

Upvotes: 2

Views: 83

Answers (1)

luk2302
luk2302

Reputation: 57124

Your problem is that 8 does not represent August but September, and the 23rd of September is more or less 52 days from now. The month is 0-indexed.

Solution: use 7 for August.

See e.g. https://stackoverflow.com/a/344400/2442804 for an attempt at explaining why.

Upvotes: 3

Related Questions