繁体   English   中英

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

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

我有以下任务:

“编写一个Java控制台应用程序来计算年,月和日中两个日期之间的持续时间。用户应该输入两个日期作为输入,然后程序将显示这两个日期之间的时差结果。”

有没有人可以尝试重写的任何示例? 如果我能够将概念写出来并观察正在发生的事情,那么概念对我来说往往更好,更有意义。 有什么建议的方法可以解决这个问题吗? 我浏览了许多类似于我的问题的Stack Overflow帖子,但是我所遇到的似乎都没有包含用户输入两个有问题的日期的情况。

附带说明一下,如果这很重要,那么我将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#getMillis()并找到您感兴趣的两个日期的毫秒数之间的差,然后将其转换为您感兴趣的单位手动(阅读:更容易出错)。

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的优势,该Java 8包括一个以@Andy推荐的出色的Joda库为模型的升级日期/时间库。 两者都应该合适。

Java 8之前的日期/时间功能很糟(以创造一个技术术语)。 在日期和日历类中,朱利安日的遗漏是显而易见的。 甚至Oracle也承认这一点-参见http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

如果您决定使用旧式的Java Date类,请非常小心。 大多数语言环境都有夏令时,因此一年中有一天的时长为23小时(时钟向前移动),而另一天的时长为25小时(时钟向后移动)。 日期之间的毫秒数除以86400000即可满足此要求。 只要确保您编码并包括针对这些极端情况的单元测试即可。

这似乎是学术性的,但我曾经参与整理有关紧急车辆响应时间的不准确报告。 由于忽略了夏令时,因此一些响应花费了一个多小时,并且一些设备在收到警报前55分钟到达。 可以想象,这导致了统计数据的严重偏差。 时间处理不当可能会对现实产生影响。

我假设您必须自己编写所有内容。 考虑到您提到这是“绝对的初学者”任务。 我要做的是使用Scanner读取日期,然后将其转换为天数并计算天数差,然后将其转换回“ YMD”格式并打印。 我会注意到,我将所有“检查”遗漏了,以便您填写。

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

请记住,转换时必须检查一年/月中的天数...

基于标准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");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM