我一直在尝试为Android应用创建一个将圣诞节倒计时的代码。
这是我到目前为止所做的。
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(new Date(0)); /* reset */
thatDay.set(Calendar.DAY_OF_MONTH, 25);
thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);
Calendar today = Calendar.getInstance();
while (true)
{
long diff = thatDay.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600); // % 24 not needed
}
然而,当我尝试循环它时,它会产生太多输出。如何每秒显示代码更新?
请帮助!!
答案 0 :(得分:1)
你的循环
while (true) {
...
}
永远不会终止,因为你内部没有break;
。
相反,请尝试for
循环:
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date xmas = f.parse("2014-12-25");
for (long i = System.currentTimeMillis(); i < xmas.getTime(); i += TimeUnit.HOURS.toMillis(1)) {
long hours = TimeUnit.MILLISECONDS.toHours(xmas.getTime() - i);
// do something with hours
}
这几个小时循环直到圣诞节,但你可以很容易地改变它。
请注意使用TimeUnit类而不是多行数学。
答案 1 :(得分:1)
最好使用ScheduledExecutorService,它会重复到达目的地时间。 它的优点是它不会在打印输出之间使用您的处理器时间。
final ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1);
final Calendar thatDay = new GregorianCalendar(2014, 11, 25);
final Calendar today = Calendar.getInstance();
service.schedule(new Runnable() {
@Override
public void run() {
long diff = thatDay.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600); // % 24 not needed
if (diff > 0) {
ses2.schedule(this, 1, TimeUnit.SECONDS);
}
}
}, 1, TimeUnit.SECONDS);