1
votes

How can I pass TimePickerDialog value to countDown timer? Here is my countdown timer code:

public class MyCountDown extends CountDownTimer {

    public MyCountDown(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onTick(long millisUntilFinished) {  
        long sec = millisUntilFinished/1000;
        String t = String.format("%02d:%02d:%02d", sec / 3600,(sec % 3600) / 60, (sec % 60));
        t1.setText("Remaining time:---"+t);
    }   
} 

And my time picker output is 3:23 PM. How can I pass this time to countdown timer? Please help me, thanks in advance.

1
I also tried to convert time to millis but output is not proper. - Madhav_nimavat
please show how you had parsed this to milliseconds.. - Opiatefuchs
String dt_time = "4/9/2016"+" "+"3:17 PM"; SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a"); try { Date date = format.parse(dt_time); milliseconds = date.getTime(); } catch (Exception e) { } - Madhav_nimavat

1 Answers

0
votes

Like you have described in your comment, You try to parse a date like this:

String dt_time = "4/9/2016"+" "+"3:17 PM"; 

with a SimpleDateFormat like this:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a");

So you get an exception. To parse a date like your date String, you need this SimpleDateFormat

"d/M/yyyy h:mm a"

or you have to change your date string to:

"04/09/2016"+" "+"03:17 PM";

You are using a one numbered format for Your day, month and hour in your string, but try to parse it with a double numbered format. I noticed that the API from SimpleDateFormat has changed the description. The meaning is the same, but I think the old API description was better to understand. Look here: SimpleDateFormat

EDIT

Your code should be something like this:

String dt_time = "4/9/2016"+" "+"3:17 PM"; 
SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy h:mm a");
Date date = format.parse(dt_time);
long millis = date.getTime();

MyCountDown mMyCountDown = new MyCountDown(millis,1000);
mMyCountDown.start();

EDIT 2

So now another assumption: The user selects some time in the future, let´s say 5:00 PM, and now it´s 4:00 PM. Then you have to get the current time like:

Calendar cal = Calendar.getInstance();
long currentMillis = cal.getTimeInMillis();

Then you have the millis from your timepicker in my example above. These are in the future. then you need to substract the current time from these millis:

long millisToCount = millis - currentMillis;

Then pass this to the timer:

 MyCountDown mMyCountDown = new MyCountDown(millisToCount,1000);
 mMyCountDown.start();

Then the timer should count down until the selected time is coming up. Is that what you want?