简体   繁体   中英

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 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. 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). Then my last part of the algorithm is to calculate how many days have passed in this present year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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