[英]How can I pass TimePickerDialog value to countdown timer in android
How can I pass TimePickerDialog
value to countDown timer? 如何将TimePickerDialog
值传递给countDown计时器? 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. 我的时间选择器输出是下午3:23。 How can I pass this time to countdown timer? 我如何将这段时间传递给倒数计时器? Please help me, thanks in advance. 请帮助我,提前谢谢。
Like you have described in your comment, You try to parse
a date like this: 就像您在评论中描述的那样,您尝试parse
的日期:
String dt_time = "4/9/2016"+" "+"3:17 PM";
with a SimpleDateFormat
like this: 使用像这样的SimpleDateFormat
:
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
要解析日期String
date
类的日期,您需要使用此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. 您在字符串中使用一个编号格式的日期,月份和小时,但尝试使用双编号格式parse
它。 I noticed that the API from SimpleDateFormat
has changed the description. 我注意到SimpleDateFormat
的API已经改变了描述。 The meaning is the same, but I think the old API description was better to understand. 意思是一样的,但我认为旧的API描述更好理解。 Look here: SimpleDateFormat 看这里: SimpleDateFormat
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();
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. 所以现在另一个假设是:用户选择将来的某个时间,假设是下午5:00,现在是下午4:00。 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? 那是你要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.