您好,我想创建一个黑莓应用程序进行倒计时和计算日期,例如,如果您输入您的出生日期,它应该生成多少年,几个月,几天,几小时和几分钟已经过去,我想知道如何创建适当的逻辑来创建此应用程序。提前谢谢....
答案 0 :(得分:1)
使用基本的Java SE 6 API,最好的选择是java.util.Calendar
。它也可以在Java ME中找到。由于没有内置设施来计算周期,因此只需要很多代码来正确计算经过的时间。您需要克隆日历实例并在计数循环中添加年,月和日,直到它到达结束日期。你不能只是按秒来划分,因为这不会占用闰年,白天的节省和这种东西。在计算完之后,您可以按常规方式将残余分为小时,分钟和秒。
这是一个启动示例:
package com.stackoverflow.q2936686;
import java.util.Calendar;
public class ElapsedTimeWithCalendar {
public static void main(String[] args) throws Exception {
Calendar birthDate = Calendar.getInstance();
birthDate.set(1978, 3 - 1, 26, 12, 35, 0); // My birthdate.
Calendar now = Calendar.getInstance(); // Now.
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) birthDate.clone(); // Otherwise changes are been reflected.
elapsed[0] = elapsed(clone, now, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, now, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, now, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (now.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (now.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (now.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
System.out.format("%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n", elapsed);
}
private static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
}
非常详细,是的。但是,在Java SE 7中,将出现一个新的日期和时间API(JSR-310),它将与当前可用的JodaTime API类似。这是一个启动示例,它看起来如何使用JodaTime:
DateTime birthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period elapsed = new Period(birthDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" years, ")
.appendMonths().appendSuffix(" months, ")
.appendDays().appendSuffix(" days, ")
.appendHours().appendSuffix(" hours, ")
.appendMinutes().appendSuffix(" minutes, ")
.appendSeconds().appendSuffix(" seconds")
.toFormatter();
System.out.println(formatter.print(elapsed));
有什么区别,对吧? :)