Java 如何创建圣诞节倒计时
我一直在尝试为android应用程序创建一个圣诞节倒计时的代码 这就是我目前所拥有的Java 如何创建圣诞节倒计时,java,Java,我一直在尝试为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 t
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
}
然而,当我尝试循环它时,它会产生太多的输出。如何显示每秒更新的代码
请帮忙 你的循环
while (true) {
...
}
永远不要终止,因为你没有中断代码>在它里面
相反,请尝试一个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
}
import java.text.simpleDataFormat;
导入java.util.concurrent.TimeUnit;
SimpleDataFormat f=新的SimpleDataFormat(“yyyy-MM-dd”);
日期xmas=f.parse(“2014-12-25”);
对于(long i=System.currentTimeMillis();i
这个循环会持续几个小时直到圣诞节,但是你可以很容易地改变它
请注意使用类而不是大量的数学运算。如果使用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);
甚至在圣诞节之后;)轻微的打字错误,i
尖锐的物体在java中是危险的。@compass是的,我在iPhone上翻代码时有点打字错误。修正了,谢谢波希米亚人!我在爪哇是个十足的傻瓜!我试着输入代码,但编译器运行起来有困难。有什么想法吗?谢谢