简体   繁体   English

如何以天为单位找到两个日期之间的差异?

[英]How to find the difference between two dates in days?

First of all.首先。 I have looked at the other existing threads about similiar questions but they do cover a general way to calculate a person's age in years, months and days.我已经查看了有关类似问题的其他现有线程,但它们确实涵盖了以年、月和日为单位计算一个人年龄的一般方法。

I am wondering if I could do something the long way instead of the short way.我想知道我是否可以做一些长期而不是短期的事情。 In-order to calculate how old a person is in days, I first get the current date with the help of LocalDate:为了计算一个人的年龄,我首先在 LocalDate 的帮助下获取当前日期:

        LocalDate date = LocalDate.now();
        int years = 0, months = 0, days = 0;

        int currYear = date.getYear();
        int currMonth = date.getMonthValue();
        int currDay = date.getDayOfMonth();

To get the user's birthdate, I use a Scanner:为了获取用户的生日,我使用扫描仪:

    Scanner scanner = new Scanner(System.in);

int userDate;
System.out.println("When are you born? - YYYYMMDD:");
userDate = scanner.nextInt();

int inputYear = userDate / 10000;
int inputMonth = (userDate / 100) % 100;
int inputDay = userDate % 100;

How would I calculate the difference between these two dates without using the already defined methods aka:如果不使用已经定义的方法,我将如何计算这两个日期之间的差异:

GregorianCalendar userInput= new GregorianCalendar(inputYear, inputMonth - 1, inputDay);

long difference = (greg.getTimeInMillis() - userInput.getTimeInMillis()); long total = difference / 1000 / 60 / 60 / 24; total += counter; System.out.println("You are " + total + " days old");

Any tips, pointers in directions would be highly appriciated!任何提示,方向指示都将受到高度评价!

Thanks in advance.提前致谢。 :) :)

You shouldn't mix various Date-Objects and calculations in and expect it to work.你不应该混合各种日期对象和计算,并期望它工作。 Use the SimpleDateFormat to parse/output Dates easily without any huge efford since it'll do it for you already.使用SimpleDateFormat轻松解析/输出日期,无需任何巨大的负担,因为它已经为您完成了。 You'll get the usual Date which you can get the times from.您将获得通常的日期,您可以从中获取时间。 From there on its only calculation and should be fairly simple.从那里开始它的唯一计算应该是相当简单的。

If you need help with Dates, you should check this simple Tutorial for more information.如果您需要有关日期的帮助,您应该查看这个简单的教程以获取更多信息。

I did a simple algorithm.我做了一个简单的算法。 First I start off by calculating how many days are left in the year the user was born.首先,我首先计算用户出生​​的那一年还剩下多少天。 Once I have those I start adding the days towards the current year - 1 (meaning 2015).一旦我有了这些,我就开始添加当前年份的天数 - 1(即 2015 年)。 Then my last part of the algorithm is to calculate how many days have passed in this present year.然后我算法的最后一部分是计算今年过去了多少天。

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

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