我正在使用Android CountDownTimer作为我的应用程序的计时器。应用程序应获取当前时间并将其减去一段时间以开始倒计时,例如,如果我们在6/4/2018晚上10点。我希望计数器倒计时到6/5/2018,它将从0.23.59.59开始,而它应该从0.1.59.59开始,因为距离目标只有两个小时。这是我的代码:
Calendar start_calendar = Calendar.getInstance(TimeZone.getDefault());
Calendar end_calendar = Calendar.getInstance();
start_calendar.set(start_calendar.get(Calendar.YEAR), start_calendar.get(Calendar.MONTH), start_calendar.get(Calendar.DAY_OF_MONTH));
end_calendar.set(2018, 5, 5); // 10 = November, month start at 0 = January
long start_millis = start_calendar.getTimeInMillis(); //get the start time in milliseconds
long end_millis = end_calendar.getTimeInMillis(); //get the end time in milliseconds
long total_millis = (end_millis - start_millis); //total time in milliseconds
//1000 = 1 second interval
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); //You can compute the millisUntilFinished on hours/minutes/seconds
}
@Override
public void onFinish() {
timer.setText("finish!");
}
};
cdt.start();
任何帮助都将不胜感激。