我正在编写一个程序,该程序的标题显示当前时间。我想允许用户修改日期/时间设置。但在用户修改后,我无法让日历保持最新状态。它始终显示用户输入的值。例如:
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(cal.getTime());
假设第一个输出是
Mon Feb 18 11:33:07 CET 2013
我想要的是在 2 秒后得到第二个输出
Mon Sep 18 11:33:09 CET 2013 // Month = Sep and Seconds = 09
我得到的是
Mon Sep 18 11:33:07 CET 2013 // Month = Sep, seconds don't change, still 07!!
如果我在第二个输出之前添加 cal = Calendar.getInstance();
,我会得到
Mon Feb 18 11:33:09 CET 2013 // Seconds = 09, month doesn't change, still Feb!!
我认为一定有一个我找不到的简单明了的实现。
更新:我无法在我正在使用的嵌入式系统上使用 DateFormat。
最佳答案
日历未更新,因为日历的时间将在创建对象时或您明确设置时间时设置。在你的情况下,它设置在这一行之后。
Calendar cal = Calendar.getInstance();
如果你真的想这样做,你需要找到耗时并增加日历时间,如下所示,
long startTime = System.currentTimeMillis(); // Process start time
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Calculating elapse time
long elapsedTime = System.currentTimeMillis() - startTime;
// Incrementing the calendar time based on elapsed time
cal.setTimeInMillis(cal.getTime().getTime() + elapsedTime);
关于java - 如何在修改后保持 Java 日历更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14934372/