2

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

  • And what is the output you receive / expect. – luk2302 Aug 02 '20 at 18:14
  • for example. I want a coutdown for Christmas. So the user sees how many days, hours, minutes and seconds it still takes for Christmas. – Dennis Joch Aug 02 '20 at 18:26
  • That is neither an input nor an output in terms of the actually running method, what is the input date, what is the output date, what is the resulting text of the `timer` vs. what do you actually want to be its content? Not paraphrased, but actual values. – luk2302 Aug 02 '20 at 18:27
  • with `end_calendar.set(2020, 8, 23);` i put the end of time. Where I tried using `Date currentTime = Calendar.getInstance (). GetTime ();` I had only trash. Sorry but this is the first time that i work with time values at java. – Dennis Joch Aug 02 '20 at 18:37
  • WHAT IS THE ACTUAL VALUE YOU GET IN THE `timer`? – luk2302 Aug 02 '20 at 18:39
  • Oh boy... Sorry if I don't understand what you mean immediately. You don't have to scream. timer is now: 51:23:59:41 – Dennis Joch Aug 02 '20 at 18:43
  • 1
    See, now I can look at those values and think "hey, they are NOT complete garbage, they are just a little off" and go figure out why that is. – luk2302 Aug 02 '20 at 18:57
  • As an aside consider not using `Calendar` since it is poorly designed and outdated. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Aug 13 '20 at 15:12

1 Answers1

3

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.

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • I appreciate.... thx!!!! sometimes it's too easy. ^^ – Dennis Joch Aug 02 '20 at 19:02
  • 1
    @DennisJoch after a rocky start I am happy to help, working with dates is a pain, especially with the default java date api. – luk2302 Aug 02 '20 at 19:03
  • I still have an addendum. Do you have an idea how to syronize the countdown with the current local time? – Dennis Joch Aug 02 '20 at 19:17
  • @DennisJoch if you plan on doing more with dates and times you might want to move from `java.util.*` to `java.time.*`, there you have proper concepts of `LocalDate`, etc. It gets a little bit more complex because e.g. you actually have to think about the different things a point in time actually means and how timezones affect / don't affect that. See e.g. https://shorturl.at/iwBH8 . For your specific question: I am not sure I understand what you want to achieve. What you certainly have to think about is if you want to countdown to a date in UTC or a date in any specific local timezone. – luk2302 Aug 02 '20 at 19:24
  • @DennisJoch it depends on wether you want someone in the US to see the same countdown or a different countdown because December 1st is closer for you in Germany as it is for someone in New York, etc.... – luk2302 Aug 02 '20 at 19:27
  • Now it work with `CountdownView myCountdownView = view.findViewById(R.id.cdv); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String countDate = "22-08-2020 00:00:00"; Date now = new Date(); try { Date date = sdf.parse(countDate); long currentTime = now.getTime(); long newYearDate = date.getTime(); long countDownToNewYear = newYearDate - currentTime; myCountdownView.start(countDownToNewYear); }catch (ParseException e){ e.printStackTrace(); }` – Dennis Joch Aug 02 '20 at 20:05
  • So i use [Github](https://github.com/iwgang/CountdownView) ... I try my best to rebuild this function. Thx for u help. – Dennis Joch Aug 02 '20 at 20:07