JAVA 控制台应用程序以 MM/DD/YYYY 格式计算两个用户指定日期之间的持续时间

JAVA console app to calculate the duration between two user specified dates in MM/DD/YYYY format

我有以下任务:

"Write a Java console application to calculate the duration between two dates in Years, Months and Days. The user should enter two dates as input, then the program will show the result of the difference in time between these two dates."

有没有人有任何我可以尝试重写的例子?如果我能够把它写出来并在我写的过程中看到发生了什么,那么概念对我来说往往会更好地坚持并且更有意义。任何建议的方法来解决这个问题?我浏览了许多与我的问题类似的 Stack Overflow 帖子,但我遇到的 none 似乎包含了用户输入有问题的两个日期的场景。

附带说明一下,如果重要的话,我将 Eclipse 与 JDK 8 一起使用。

编辑: 这是我的最终结果。再次感谢大家的帮助!

import java.util.Scanner; // Calling in Scanner to get some user input.
import java.time.LocalDate; // Importing LocalDate
import java.time.Period;  // Importing Period

class TimeDurationCalculator {

    // Creating a main method.
    public static void main(String[] args) {

        System.out.println("DIFFERENCE IN TIME CALCULATOR v 0.00.000.0002");
        System.out.println("BY: Matt Anderson for Grand Circus Detroit's Java Bootcamp");
        System.out.println("");
        System.out.println("About This Program: This program will calcuate the difference in");
        System.out.println("two user specified dates in terms of months, days, and years.");
        System.out.println("");

        // Prompt for oldest date input by user.
        System.out.print("Enter the oldest date in YYYY-MM-DD format: ");

        // Creating a Scanner object
        Scanner scanner = new Scanner(System.in);

        String oldestDateString = scanner.nextLine();

        LocalDate oldestDate = LocalDate.parse(oldestDateString);

        System.out.println("You entered " + oldestDate + " for your oldest date.");
        System.out.print("Enter the most recent date in YYYY-MM-DD format: ");

        String newestDateString = scanner.nextLine();
        LocalDate newestDate = LocalDate.parse(newestDateString);
        System.out.println("You entered " + newestDate + " for your most recent date.");

        Period difference = oldestDate.until(newestDate);

        int days = difference.getDays();
        int months = difference.getMonths();
        int years = difference.getYears();
        scanner.close();

        System.out.println("Your time difference is: " + months + " Months, " + days + " Days, and " + years + " Years.");
    }
}

使用 joda DateTime

然后你可以用这样的方法计算某人的年龄:

Years.yearsBetween(mBirthDate, DateTime.now(DateTimeZone.UTC)).getYears();

或者您可以使用本机 Java Date 但是您可能需要调用 Date#getMillis() 并找出您感兴趣的两个日期的毫秒数之间的差异in 然后手动将其转换为您感兴趣的单位(阅读:更容易出错)。

PlainTimestamp t1 = PlainTimestamp.of(1984, 12, 16, 7, 45, 55);
PlainTimestamp t2 = PlainTimestamp.of(2014, 9, 9, 19, 46, 45);
IsoUnit[] units =
    {
        CalendarUnit.YEARS, CalendarUnit.MONTHS, CalendarUnit.DAYS, ClockUnit.HOURS,
        ClockUnit.MINUTES, ClockUnit.SECONDS
    };

String out= PrettyTime.of(Locale.ENGLISH).print(duration, TextWidth.WIDE);
System.out.println(out); 
// output: 29 years, 8 months, 24 days, 12 hours, 50 seconds

您拥有使用 Java 8 的优势,其中包括升级的 date/time 库,该库仿照@Andy 推荐的优秀 Joda 库。两者都应该合适。

pre-java 8 date/time 设施糟透了(创造一个技术术语)。在日期和日历 classes 中明显遗漏了儒略日。甚至 Oracle 也承认这一点 - 请参阅 http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

如果您决定使用 old-style Java 日期 class,请务必小心。大多数地区都有夏令时,所以一年中有一天是 23 小时长(时钟快进),另一天是 25 小时长(时钟倒退)。将日期之间的毫秒数除以 86400000 需要考虑到这一点。只需确保为这些边缘情况编写代码并包括单元测试即可。

这似乎很学术,但我曾经参与整理有关紧急车辆响应时间的不准确报告。由于忽略了夏令时,一些响应花费了一个多小时,并且一些单位在收到警报前 55 分钟到达。正如您可以想象的那样,这导致了严重偏差的统计数据。时间处理不当可能会产生 real-world 影响。

我假设您必须自己编写所有内容。考虑到您提到这是一项 "absolute beginners" 任务。我要做的是使用 Scanner 读取日期,然后将它们转换为天数并计算天数差异,然后将该差异转换回 "Y M D" 格式并打印出来。我会注意到我把所有 "checking" 都留了下来,让你填写。

Scanner scanner = new Scanner(System.in); // create a scanner object

int year1, year2, month1, month2, day1, day2;

// promt for input
System.out.println("Enter the first date: (format -> \"Y M D\")");

// read the 1st input
year1 = scanner.nextInt(); // assuming the input is correct
month1 = scanner.nextInt();
day1 = scanner.nextInt();

// promt for input
System.out.println("Enter the second date: (format -> \"Y M D\")");

// read the 2bd input
year2 = scanner.nextInt(); // assuming the input is correct
month2 = scanner.nextInt();
day2 = scanner.nextInt();

// convert the input to days(note that the conversion is only an approximation, not every year/day has the same amount of days)
int date1 = (year1 * 365 + month1 * 30) + day1; // I'll leave the number of days in the year/month checking to you.
int date2 = (year2 * 365 + month2 * 30) + day2;

int durationdifferance = date2 - date1; // note this CAN be negative if date1 is after date2(I'll leave it to you to deside the action needed if that's true)

// convert back (this is again only an approximation)
int year = durationdifferance / 356;
int month = (durationdifferance % 365) / 30;
int day = (durationdifferance % 365) % 30;

// output the differance
System.out.println("Differance is: " + year + " " + month + " " + day);

请记住,您必须在转换时检查 year/month 中的天数...

基于标准的解决方案 Java API.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //READ TWO DAYS FROM INPUT
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
        Scanner scanner = new Scanner(System.in);
        Date date1= format.parse(scanner.nextLine());
        Date date2= format.parse(scanner.nextLine());
        scanner.close();

        //CALCULATE DIFFERENCE IN DAYS
        long diff = date1.getTime()-date2.getTime();
        long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        diffDays = Math.abs(diffDays);
        System.out.println(diffDays);

    }
}

执行这段代码就明白了。

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first date in this format YYYY/MM/DD: ");
        String[] date1Array = sc.nextLine().split("/");
        GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(date1Array[0]),Integer.parseInt(date1Array[1])-1,Integer.parseInt(date1Array[2]));
        Date date1 = cal.getTime();
        System.out.println("Enter second date in this format  YYYY/MM/DD: ");
        String[] date2Array = sc.nextLine().split("/");
        cal = new GregorianCalendar(Integer.parseInt(date2Array[0]),Integer.parseInt(date2Array[1])-1,Integer.parseInt(date2Array[2]));
        Date date2 = cal.getTime();
        double difference = (date2.getTime() - date1.getTime())/3600000;
        if(difference < 0) difference = -difference;
        System.out.println("The difference is "+difference+" hours and "+difference/24+" days");
    }
}