日历用户输入日期?

Calendar User inputting dates?

我想添加用户输入,因为他们输入了日期,这样我以后就可以对其进行计算。我没有像下面那样设置日期,而是不知道如何做到这一点,如果有人可以帮助或指出正确的方向,那就太好了。

Calendar dueDate1 = Calendar.getInstance();
Calendar dueDate2 = Calendar.getInstance();

dueDate1.set(2015,0,1);
dueDate2.set(2014,0,1);

long time1 = dueDate1.getTimeInMillis();
long time2 = dueDate2.getTimeInMillis();

time = (time1 - time2);

long answer = time/1000/60/60/24/365;
long days = time/1000/60/60/24;


System.out.println("");
System.out.println("Difference between 2015,0,1 & 2014,0,1");
System.out.println("");
System.out.println("Years difference " + answer);
System.out.println("Days difference " + days);

如果您希望用户从控制台向您的程序输入数据,最简单的方法是使用 Scanner class.

此外,如果您使用 Joda time library,或者如果您使用 Java 8,其重新设计的日期和时间 API,而不是 "old API classes" 喜欢日历和日期。

这是一个使用 Scanner 和 Joda 时间的示例:

private void showDateDiffs() {

    Scanner sc = new Scanner(System.in);
    DateTime dueDate1 = new DateTime()
            .withYear(getInput(sc, "year", "due date 1"))
            .withMonthOfYear(getInput(sc, "month", "due date 1"))
            .withDayOfMonth(getInput(sc, "day", "due date 1"));

    DateTime dueDate2 = new DateTime()
            .withYear(getInput(sc, "year", "due date 2"))
            .withMonthOfYear(getInput(sc, "month", "due date 2"))
            .withDayOfMonth(getInput(sc, "day", "due date 2"));

    final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(String.format("\nDifference between %s & %s\n",
            df.format(dueDate1.toDate()), df.format(dueDate2.toDate())));
    System.out.println("Years difference "
            + Years.yearsBetween(dueDate2.toLocalDate(),
                    dueDate1.toLocalDate()).getYears());
    System.out.println("Days difference "
            + Days.daysBetween(dueDate2.toLocalDate(),
                    dueDate1.toLocalDate()).getDays());
}

private static int getInput(Scanner sc, String timeUnit,
        String dateIdentifier) {
    System.out.println(String.format("Input %s for %s", timeUnit,
            dateIdentifier));
    return sc.nextInt();
}