1

I'm using CountDownTimer in my Application and it's showing wrong hours. this is what i tried.

long miliSecsDate = milliseconds ("2017-11-18 12:35");

Convert date and time in to miliseconds

public long milliseconds(String date)
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try
                {
                    Date mDate = sdf.parse(date);
                    long timeInMilliseconds = mDate.getTime();
                    return timeInMilliseconds;
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                return 0;
            }

Countdown timer

public void showCountdown(long miliSecsDate){
        new CountDownTimer(miliSecsDate, 1000) {
            public void onTick(long millisUntilFinished) {
                long seconds= TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);

                int minutes = (int)(seconds % 3600) / 60;
                int hours = (int)seconds / 3600;
                seconds = seconds % 60;
                Log.d("time",""+hours+" : "+minutes+" : "+seconds);
          }
            public void onFinish() {
                txtRemainingTime.setText("done!");
            }

        }.start();
    }

my Log cat showing like below

D/time: 419719 : 3 : 43

Ronak Thakkar
  • 2,355
  • 6
  • 26
  • 41
user8164155
  • 117
  • 1
  • 16

1 Answers1

0

Try using:

    String myDate = "2017-11-18 12:35";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    long seconds = millis/1000;
    long sec = seconds % 60;
    long min = (seconds / 60) % 60;
    long hrs = (seconds / (60 * 60)) % 24;


    Log.d("time",""+hrs+" : "+min+" : "+sec);

If you want to use TimeUnit class Refer link

Firoz Memon
  • 3,027
  • 2
  • 17
  • 28