日历用户输入日期?

时间:2015-03-14 23:32:08

标签: java date calendar

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

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);

1 个答案:

答案 0 :(得分:0)

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

此外,如果您使用Joda time library,或者如果您使用的是Java 8,重新设计的日期和时间API,而不是日历和日期等“旧API类”,日期计算将变得更加容易。

以下是使用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();
}