使用公历与当前日期进行比较,无需外部课程

时间:2016-04-27 04:44:36

标签: java calendar

我应该问用户他们的年龄,作为回报,我应该检查他们过了多少天。我已经尝试过在这里搜索,但我无法完成如何操作。

条件:将GregorianCalendar日期作为参数的方法,并返回该日期与今天之间的天数差异。 我不能使用任何外部类。

这是我未完成的代码:

public static void main(String[] args) {
    int day;
    int month;
    int year;
    int difference;
    Scanner scanIn = new Scanner(System.in);

    System.out.println("Please enter your birth date.");
    System.out.println("Please enter the month you were born in (mm)");
    month = scanIn.nextInt();
    System.out.println("Please enter the day you were born in (dd)");
    day = scanIn.nextInt();
    System.out.println("Please enter the year you were born in (yyyy)");
    year = scanIn.nextInt();

    GregorianCalendar greg = new GregorianCalendar(year, month, day);

    difference = getDifference(greg);
    month = greg.get(Calendar.MONTH) + 2;
    year = greg.get(Calendar.YEAR);

    //System.out.println("Year is " + year);
    //System.out.println("Month " + month);

}

public static int getDifference(GregorianCalendar greg) {
     Calendar now = new GregorianCalendar();
     int difference;
     System.currentTimeMillis.greg(); 

    difference = greg - now;
    return difference;
}

我不明白如何发挥作用?

我的导师建议我们用毫秒来解决问题,但我已经花了4个小时试图解决这个问题而且我不明白这一点。

如何获取当前日期,月份和年份?

2 个答案:

答案 0 :(得分:1)

建议在Java 8中使用new date API而不是Calendar API。特别是,您可以使用here所述的方法ChronoUnits.DAYS.between()。我建议这个:

    LocalDate dob = LocalDate.of(year, month, day);
    LocalDate now = LocalDate.now();
    difference=(int)ChronoUnit.DAYS.between(dob, now);

    System.out.println("Days since date of birth: " + difference);

您可以轻松地检查结果与旧界面相同:

    GregorianCalendar greg = new GregorianCalendar(year, month-1, day);
    Calendar nowCal = new GregorianCalendar();      
    long deltaMillis = nowCal.getTime().getTime() - greg.getTime().getTime();

    System.out.println("Days since date of birth: " + deltaMillis/(1000*60*60*24));

请注意,Calendar接口从0开始计算月份,新API从1开始计算。

我希望它有所帮助。

答案 1 :(得分:1)

如果你只能使用GregorianCalendar,一种方法是将日历的两个实例转换为毫秒表示,通过getTimeInMillis,减去它们,然后通过除以它来计算代表的天数(24 * 60 * 60 * 1000)。

例如:

public static int countDaysSince(GregorianCalendar pastDate) {
    GregorianCalendar now = GregorianCalendar.getInstance();

    long difference = pastDate.getTimeInMillis() - now.getTimeInMillis();
    return difference / (24 * 60 * 60 * 1000); // 24 hours, 60 minutes, 60 seconds, 1000 milliseconds
}

应该这样做。